<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="MyBatis 详解, Gtwff">
    <meta name="description" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="referrer" content="no-referrer-when-downgrade">
    <!-- Global site tag (gtag.js) - Google Analytics -->

<script async src="https://www.googletagmanager.com/gtag/js?id="></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag() {
        dataLayer.push(arguments);
    }

    gtag('js', new Date());
    gtag('config', '');
</script>


    <title>MyBatis 详解 | Gtwff</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 5.4.0"></head>



   <style>
    body{
       background-image: url(https://cdn.jsdelivr.net/gh/Tokisaki-Galaxy/res/site/medias/background.jpg);
       background-repeat:no-repeat;
       background-size:cover;
       background-attachment:fixed;
    }
</style>



<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">Gtwff</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">Gtwff</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://gitee.com/kuangty/kuangty" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://gitee.com/kuangty/kuangty" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/10.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">MyBatis 详解</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/MyBatis-%E8%AF%A6%E8%A7%A3/">
                                <span class="chip bg-color">MyBatis 详解</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/MyBatis/" class="post-category">
                                MyBatis
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2022-02-19
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2022-02-19
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    12k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    53 分
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/libs/prism/prism.css">
        

        
        <!-- 代码块折行 -->
        <style type="text/css">
            code[class*="language-"], pre[class*="language-"] { white-space: pre-wrap !important; }
        </style>
        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h1 id="一、第一个Mybatis项目"><a href="#一、第一个Mybatis项目" class="headerlink" title="一、第一个Mybatis项目"></a>一、第一个Mybatis项目</h1><blockquote>
<p>采用接口式编程</p>
</blockquote>
<h2 id="1-创建maven工程并导包"><a href="#1-创建maven工程并导包" class="headerlink" title="1. 创建maven工程并导包"></a>1. 创建maven工程并导包</h2><p>可以使用maven在线下载依赖，这里因为我已经下载好了jar包，直接导入就行了</p>
<p>新建一个lib文件夹，导入 <code>mysql 驱动</code> 和 <code>mybatis-3.4.1</code>  <strong>并将lib文件夹右键 add as library</strong></p>
<p>可在官网下载 mybatis 的 jar 包 <a target="_blank" rel="noopener" href="https://github.com/mybatis/mybatis-3/">mybatis 官网</a></p>
<p><img src="https://img-blog.csdnimg.cn/20200327104450139.png" alt="img"></p>
<h2 id="2-创建数据库表和对应的-JavaBean"><a href="#2-创建数据库表和对应的-JavaBean" class="headerlink" title="2. 创建数据库表和对应的 JavaBean"></a>2. 创建数据库表和对应的 JavaBean</h2><p>数据库表</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">CREATE</span> <span class="token keyword">TABLE</span> <span class="token punctuation">`</span>tbl_employee<span class="token punctuation">`</span> <span class="token punctuation">(</span>
  <span class="token punctuation">`</span>id<span class="token punctuation">`</span> <span class="token keyword">int</span><span class="token punctuation">(</span><span class="token number">11</span><span class="token punctuation">)</span> <span class="token operator">NOT</span> <span class="token boolean">NULL</span> <span class="token keyword">AUTO_INCREMENT</span><span class="token punctuation">,</span>
  <span class="token punctuation">`</span>last_name<span class="token punctuation">`</span> <span class="token keyword">varchar</span><span class="token punctuation">(</span><span class="token number">255</span><span class="token punctuation">)</span> <span class="token keyword">DEFAULT</span> <span class="token boolean">NULL</span><span class="token punctuation">,</span>
  <span class="token punctuation">`</span>gender<span class="token punctuation">`</span> <span class="token keyword">char</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span> <span class="token keyword">DEFAULT</span> <span class="token boolean">NULL</span><span class="token punctuation">,</span>
  <span class="token punctuation">`</span>email<span class="token punctuation">`</span> <span class="token keyword">varchar</span><span class="token punctuation">(</span><span class="token number">255</span><span class="token punctuation">)</span> <span class="token keyword">DEFAULT</span> <span class="token boolean">NULL</span><span class="token punctuation">,</span>
  <span class="token keyword">PRIMARY</span> <span class="token keyword">KEY</span> <span class="token punctuation">(</span><span class="token punctuation">`</span>id<span class="token punctuation">`</span><span class="token punctuation">)</span>
<span class="token punctuation">)</span> <span class="token keyword">ENGINE</span><span class="token operator">=</span><span class="token keyword">InnoDB</span> <span class="token keyword">AUTO_INCREMENT</span><span class="token operator">=</span><span class="token number">2</span> <span class="token keyword">DEFAULT</span> <span class="token keyword">CHARSET</span><span class="token operator">=</span>utf8<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>对应的 JavaBean</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Employee</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">Integer</span> id<span class="token punctuation">;</span>
    <span class="token class-name">String</span> lastName<span class="token punctuation">;</span> <span class="token comment">//字段名最好和数据库中的字段一致，如果不一致，可在sql语句中起别名</span>
    <span class="token class-name">String</span> gender<span class="token punctuation">;</span>
    <span class="token class-name">String</span> email<span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token class-name">Integer</span> <span class="token function">getId</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> id<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">setId</span><span class="token punctuation">(</span><span class="token class-name">Integer</span> id<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>id <span class="token operator">=</span> id<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">getLastName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> lastName<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">setLastName</span><span class="token punctuation">(</span><span class="token class-name">String</span> lastName<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>lastName <span class="token operator">=</span> lastName<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">isGender</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> gender<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">setGender</span><span class="token punctuation">(</span><span class="token class-name">String</span> gender<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>gender <span class="token operator">=</span> gender<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">getEmail</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> email<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">setEmail</span><span class="token punctuation">(</span><span class="token class-name">String</span> email<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>email <span class="token operator">=</span> email<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> <span class="token string">"Employee&#123;"</span> <span class="token operator">+</span>
                <span class="token string">"id="</span> <span class="token operator">+</span> id <span class="token operator">+</span>
                <span class="token string">", lastName='"</span> <span class="token operator">+</span> lastName <span class="token operator">+</span> <span class="token string">'\''</span> <span class="token operator">+</span>
                <span class="token string">", gender="</span> <span class="token operator">+</span> gender <span class="token operator">+</span>
                <span class="token string">", email='"</span> <span class="token operator">+</span> email <span class="token operator">+</span> <span class="token string">'\''</span> <span class="token operator">+</span>
                <span class="token string">'&#125;'</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>此处的 lastName 设置了和数据库中的字段 last_Name 是不一致的，我们在后面的配置文件中需要给数据库字段起对应的别名，否则会出错。</p>
<h2 id="3-创建Mybatis全局配置文件"><a href="#3-创建Mybatis全局配置文件" class="headerlink" title="3. 创建Mybatis全局配置文件"></a>3. 创建Mybatis全局配置文件</h2><p>MyBatis 的全局配置文件包含了影响 MyBatis 行为甚深 的设置（settings）和属性（properties）信息、如数据 库连接池信息等。指导着MyBatis进行工作。我们可以 参照官方文件的配置示例</p>
<p>新建 conf 文件夹，<strong>并右键 make Directory as source root</strong></p>
<p>建立 <code>mybatis-config.xml</code> 全局配置文件</p>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token prolog">&lt;?xml version="1.0" encoding="UTF-8" ?></span>

<span class="token doctype"><span class="token punctuation">&lt;!</span><span class="token doctype-tag">DOCTYPE</span> <span class="token name">configuration</span>  <span class="token name">PUBLIC</span> <span class="token string">"-//mybatis.org//DTD Config 3.0//EN"</span>  <span class="token string">"http://mybatis.org/dtd/mybatis-3-config.dtd"</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>configuration</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>environments</span> <span class="token attr-name">default</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>development<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>environment</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>development<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>transactionManager</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>JDBC<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>dataSource</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>POOLED<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
                <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>property</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>driver<span class="token punctuation">"</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.mysql.jdbc.Driver<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
                <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>property</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>url<span class="token punctuation">"</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>jdbc:mysql://localhost:3306/mybatis<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
                <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>property</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>username<span class="token punctuation">"</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>root<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
                <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>property</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>password<span class="token punctuation">"</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>root<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>dataSource</span><span class="token punctuation">></span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>environment</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>environments</span><span class="token punctuation">></span></span>

    <span class="token comment">&lt;!--将我们写好的sql映射文件注册到全局配置文件中--></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>mappers</span><span class="token punctuation">></span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>mapper</span> <span class="token attr-name">resource</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>EmployeeMapper.xml<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>mappers</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>configuration</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>mappers 中注册的 sql 映射文件如下</p>
<h2 id="4-创建一个Dao层接口"><a href="#4-创建一个Dao层接口" class="headerlink" title="4. 创建一个Dao层接口"></a>4. 创建一个Dao层接口</h2><p>在该接口中定义要执行的方法</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">EmployeeMapper</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">public</span> <span class="token class-name">Employee</span> <span class="token function">getEmpById</span><span class="token punctuation">(</span><span class="token class-name">Integer</span> id<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<h2 id="5-创建sql映射文件-Mapper"><a href="#5-创建sql映射文件-Mapper" class="headerlink" title="5. 创建sql映射文件 Mapper"></a>5. 创建sql映射文件 Mapper</h2><p>映射文件的作用就相当于是定义数据库如何工作，编写sql语句。这也是我们使用MyBatis时编写的最多的文件。</p>
<p>同样在 conf 文件夹下，创建 <code>EmployeeMapper.xml</code> 用来编写 sql 语句</p>
<p>我们采用接口式编程，将接口中的方法和该映射文件绑定起来</p>
<ul>
<li>修改名称空间 namespace 为接口的全类名</li>
<li>修改 id 为接口的方法名</li>
</ul>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token prolog">&lt;?xml version="1.0" encoding="UTF-8" ?></span>
<span class="token doctype"><span class="token punctuation">&lt;!</span><span class="token doctype-tag">DOCTYPE</span> <span class="token name">mapper</span>  <span class="token name">PUBLIC</span> <span class="token string">"-//mybatis.org//DTD Mapper 3.0//EN"</span>  <span class="token string">"http://mybatis.org/dtd/mybatis-3-mapper.dtd"</span><span class="token punctuation">></span></span>
<span class="token comment">&lt;!--名称空间，指定为接口的全类名--></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>mapper</span> <span class="token attr-name">namespace</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.smallbeef.mybatis.dao.EmployeeMapper<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
    <span class="token comment">&lt;!--id：唯一标识
    resultType: 返回值类型
    #&#123;id&#125;：从传递过来的参数中取出id值--></span>

    <span class="token comment">&lt;!--public Employee getEmpById(Integer id)
    将唯一标识id和接口中的方法进行绑定--></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>select</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>getEmpById<span class="token punctuation">"</span></span> <span class="token attr-name">resultType</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.smallbeef.mybatis.bean.Employee<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
        select id, last_name lastName, email, gender from tbl_employee where id = #&#123;id&#125;
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>select</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>mapper</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="6-测试"><a href="#6-测试" class="headerlink" title="6. 测试"></a>6. 测试</h2><p>首先，我们加载主配置文件，生成一个 <code>SqlSessionFactory</code>，再由 SqlSessionFactory 生成一个 <code>SqlSession</code>，一个 SqlSession 就相当于我们的一个会话，类似于 JDBC 中的 一个连接 connection，在 SQL 语句执行完毕后，这个会话是可以被关闭的。</p>
<p>SqlSession 的实例不是线程安全的，因此是不能被共享的。</p>
<p>SqlSession 每次使用完成后需要正确关闭，这个 关闭操作是必须的。通常把这个关闭操作放到 finally 块中</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Test</span>
   <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test01</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">IOException</span><span class="token punctuation">&#123;</span>
       <span class="token comment">// 1. 获取sqlSessionFactory对象</span>
       <span class="token class-name">String</span> resource <span class="token operator">=</span> <span class="token string">"mybatis-config.xml"</span><span class="token punctuation">;</span>
       <span class="token class-name">InputStream</span> inputStream <span class="token operator">=</span> <span class="token class-name">Resources</span><span class="token punctuation">.</span><span class="token function">getResourceAsStream</span><span class="token punctuation">(</span>resource<span class="token punctuation">)</span><span class="token punctuation">;</span>
       <span class="token class-name">SqlSessionFactory</span> sqlSessionFactory <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">SqlSessionFactoryBuilder</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">build</span><span class="token punctuation">(</span>inputStream<span class="token punctuation">)</span><span class="token punctuation">;</span>

       <span class="token comment">// 2. 获取sqlSession实例</span>
       <span class="token class-name">SqlSession</span> sqlSession <span class="token operator">=</span> sqlSessionFactory<span class="token punctuation">.</span><span class="token function">openSession</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

       <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
           <span class="token comment">// 3. 获取接口的实现类对象</span>
           <span class="token comment">// Mybatis会为接口自动的创建一个代理对象，由代理对象去执行增删改查方法</span>
           <span class="token class-name">EmployeeMapper</span> mapper <span class="token operator">=</span> sqlSession<span class="token punctuation">.</span><span class="token function">getMapper</span><span class="token punctuation">(</span><span class="token class-name">EmployeeMapper</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

           <span class="token comment">// 4. 调用接口方法</span>
           <span class="token class-name">Employee</span> employee <span class="token operator">=</span> mapper<span class="token punctuation">.</span><span class="token function">getEmpById</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

           <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>employee<span class="token punctuation">)</span><span class="token punctuation">;</span>
       <span class="token punctuation">&#125;</span> <span class="token keyword">finally</span> <span class="token punctuation">&#123;</span>
           sqlSession<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
       <span class="token punctuation">&#125;</span>
   <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<hr>
<h1 id="二、全局配置文件"><a href="#二、全局配置文件" class="headerlink" title="二、全局配置文件"></a>二、全局配置文件</h1><p>MyBatis 的配置文件包含了影响 MyBatis 行为甚深的 设置（settings）和属性（properties）信息。文档的顶层结构如下：</p>
<ul>
<li>configuration 配置</li>
<li>properties 属性</li>
<li>settings 设置 </li>
<li>typeAliases 类型命名</li>
<li>typeHandlers 类型处理器</li>
<li>objectFactory 对象工厂 </li>
<li>plugins 插件 </li>
<li>environments 环境 </li>
<li>environment 环境变量</li>
<li>transactionManager 事务管理器</li>
<li> dataSource 数据源 </li>
<li>databaseIdProvider 数据库厂商标识 </li>
<li>mappers 映射器</li>
</ul>
<h2 id="1-properties属性"><a href="#1-properties属性" class="headerlink" title="1. properties属性"></a>1. properties属性</h2><pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>environments</span> <span class="token attr-name">default</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>development<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
       <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>environment</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>development<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
           <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>transactionManager</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>JDBC<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
           <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>dataSource</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>POOLED<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
               <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>property</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>driver<span class="token punctuation">"</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.mysql.jdbc.Driver<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
               <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>property</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>url<span class="token punctuation">"</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>jdbc:mysql://localhost:3306/mybatis<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
               <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>property</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>username<span class="token punctuation">"</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>root<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
               <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>property</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>password<span class="token punctuation">"</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>root<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
           <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>dataSource</span><span class="token punctuation">></span></span>
       <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>environment</span><span class="token punctuation">></span></span>
   <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>environments</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>相比于上述在全局配置文件中写死的方式，我们可以利用 peoperties 将数据库配置信息提取出来</p>
<p>mybatis 可以使用 properties 来引入外部 properties 配置文件的内容；</p>
<ul>
<li><code>resource</code> ：引入类路径下的资源</li>
<li><code>url</code> ：引入网络路径或者磁盘路径下的资源</li>
</ul>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>properties</span> <span class="token attr-name">resource</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>dbconfig.properties<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>properties</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>在 conf 文件夹下建立 dbconfig.properties 文件，将数据库配置信息写在此处</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">jdbc<span class="token punctuation">.</span>driver<span class="token operator">=</span><span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>mysql<span class="token punctuation">.</span>jdbc<span class="token punctuation">.</span></span>Driver</span>
jdbc<span class="token punctuation">.</span>url<span class="token operator">=</span>jdbc<span class="token operator">:</span>mysql<span class="token operator">:</span><span class="token operator">/</span><span class="token operator">/</span>localhost<span class="token operator">:</span><span class="token number">3306</span><span class="token operator">/</span>mybatis
jdbc<span class="token punctuation">.</span>username<span class="token operator">=</span>root
jdbc<span class="token punctuation">.</span>password<span class="token operator">=</span>root<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p> <strong>如果属性在不只一个地方进行了配置，那么 MyBatis 将按照下面的顺序来加载：</strong></p>
<ul>
<li>在 properties 元素体内指定的属性首先被读取。</li>
<li>然后根据 properties 元素中的 resource 属性读取类路径下属性文件或根 据 url 属性指定的路径读取属性文件，并覆盖已读取的同名属性。 </li>
<li>最后读取作为方法参数传递的属性，并覆盖已读取的同名属性</li>
</ul>
<h2 id="2-settings-设置"><a href="#2-settings-设置" class="headerlink" title="2. settings 设置"></a>2. settings 设置</h2><p>这是 MyBatis 中极为重要的调整设置，它们会改变 MyBatis 的运行时行为</p>
<p><img src="https://img-blog.csdnimg.cn/20200327115441806.png" alt="img"></p>
<p>在之后用到这些标签的时候再详细讲解，此处我们先看 <code>mapUnderscoreToCamelCase</code> 参数.</p>
<p>把该参数设置为true，则打开驼峰命名法，像我们在第一节中数据库字段<code>last_Name</code>，JavaBean字段 <code>lastName</code> ，开启了该参数后，就不需要定义别名了，Myabtis 可以实现该字段的映射</p>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token comment">&lt;!-- settings包含很多重要的设置项
	 setting:用来设置每一个设置项
		name：设置项名
		value：设置项取值
 --></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>settings</span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>setting</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>mapUnderscoreToCamelCase<span class="token punctuation">"</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>true<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>settings</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="3-typeAliases-别名处理器"><a href="#3-typeAliases-别名处理器" class="headerlink" title="3. typeAliases 别名处理器"></a>3. typeAliases 别名处理器</h2><p>类型别名是为 Java 类型设置一个短的名字，可以方便我们 引用某个类, <strong>别名不区分大小写</strong></p>
<ul>
<li><p><code>typeAlias</code> : 为某个java类型起别名</p>
<p>type: 指定要起别名的类型全类名; </p>
<p>alias: 指定新的别名。默认别名就是类名小写；</p>
  <pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>typeAliases</span><span class="token punctuation">></span></span>
       <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>typeAlias</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.atguigu.mybatis.bean.Employee<span class="token punctuation">"</span></span> <span class="token attr-name">alias</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>emp<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span> 
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>typeAliases</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre></li>
<li><p>类很多的情况下，可以<strong>批量</strong>设置别名，为这个包下的每一个类创建一个默认的别名，就是简单类名小写</p>
  <pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>typeAliases</span><span class="token punctuation">></span></span>		
<span class="token comment">&lt;!-- package:为某个包下的所有类批量起别名 
                name：指定包名（为当前包以及下面所有的后代包的每一个类都起一个默认别名（类名小写））--></span>
     <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>package</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.atguigu.mybatis.bean<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>typeAliases</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</li>
<li><p><strong>批量起别名的情况下</strong>，使用 <code>@Alias</code> 注解为某个类型指定新的别名</p>
  <pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Alias</span><span class="token punctuation">(</span><span class="token string">"emp"</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> calss <span class="token class-name">Employee</span><span class="token punctuation">&#123;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre></li>
</ul>
<br>

<p>值得注意的是，MyBatis已经为许多常见的 Java 类型内建 了相应的类型别名。它们都是大小写不敏感的，我们在 别名的时候千万不要占用已有的别名<br><img src="https://img-blog.csdnimg.cn/20200327120959191.png" alt="img" style="zoom:80%;" /></p>
<blockquote>
<p>并不推荐用别名，使用全类名可以方便的 ctrl+左键 进入该类，不用到处找别名。</p>
</blockquote>
<h2 id="4-typeHandlers-类型处理器"><a href="#4-typeHandlers-类型处理器" class="headerlink" title="4. typeHandlers 类型处理器"></a>4. typeHandlers 类型处理器</h2><p>无论是 MyBatis 在预处理语句（PreparedStatement）中 设置一个参数时，还是从结果集中取出一个值时， 都会用类型处理器将获取的值以合适的方式转换成 Java 类型<br><img src="https://img-blog.csdnimg.cn/20200327121400319.png" alt="img" style="zoom:80%;" /></p>
<h3 id="①-日期类型的处理"><a href="#①-日期类型的处理" class="headerlink" title="① 日期类型的处理"></a>① 日期类型的处理</h3><ul>
<li><p>日期和时间的处理，JDK1.8以前一直是个头疼的 问题。我们通常使用JSR310规范领导者Stephen Colebourne创建的Joda-Time来操作。1.8已经实 现全部的JSR310规范了。</p>
</li>
<li><p>日期时间处理上，我们可以使用MyBatis基于 JSR310（Date and Time API）编写的各种日期 时间类型处理器。</p>
<img src="https://img-blog.csdnimg.cn/2020032712151920.png" alt="img" style="zoom:80%;" /></li>
<li><p><strong>MyBatis3.4以前的版本需要我们手动注册这些处 理器，以后的版本都是自动注册</strong></p>
</li>
</ul>
<h3 id="②-自定义类型处理器"><a href="#②-自定义类型处理器" class="headerlink" title="② 自定义类型处理器"></a>② 自定义类型处理器</h3><p>我们可以重写类型处理器或创建自己的类型处理 器来处理不支持的或非标准的类型。</p>
<p>步骤： </p>
<ul>
<li><p>1）<code>实现org.apache.ibatis.type.TypeHandler</code> 接口或 者继承 <code>org.apache.ibatis.type.BaseTypeHandler </code></p>
</li>
<li><p>2）指定其映射某个JDBC类型（可选操作） </p>
</li>
<li><p>3）在mybatis全局配置文件中注册</p>
</li>
</ul>
<h2 id="5-plugins-插件"><a href="#5-plugins-插件" class="headerlink" title="5.  plugins 插件"></a>5.  plugins 插件</h2><p>插件是MyBatis提供的一个非常强大的机制，我们 可以通过插件来修改MyBatis的一些核心行为。插件通过<strong>动态代理</strong>机制，可以介入四大对象的任何一个方法的执行。后面会有专门的章节来介绍 mybatis 运行原理以及插件</p>
<p>先来熟悉以下四大对象</p>
<ul>
<li>执行器： <code>Executor</code>(update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)</li>
<li>参数处理器：<code>ParameterHandler</code> (getParameterObject, setParameters) </li>
<li>结果集处理器：<code>ResultSetHandler</code> (handleResultSets, handleOutputParameters) </li>
<li>sql 语句处理器：<code>StatementHandler</code> (prepare, parameterize, batch, update, query) </li>
</ul>
<h2 id="6-environments-环境"><a href="#6-environments-环境" class="headerlink" title="6. environments 环境"></a>6. environments 环境</h2><p>MyBatis可以配置多种环境，比如开发、测试和生产环境需要有不同的配置。</p>
<ul>
<li><p>每种环境使用一个 <code>environment</code> 标签进行配置并指定唯一标识符</p>
</li>
<li><p>可以通过 environments 标签中的 <code>default</code> 属性指定 一个环境的标识符来快速的切换环境</p>
  <pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>environments</span> <span class="token attr-name">default</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>dev_mysql<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>environment</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>dev_mysql<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>transactionManager</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>JDBC<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>transactionManager</span><span class="token punctuation">></span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>dataSource</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>POOLED<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
                <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>property</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>driver<span class="token punctuation">"</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>$&#123;jdbc.driver&#125;<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
                <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>property</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>url<span class="token punctuation">"</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>$&#123;jdbc.url&#125;<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
                <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>property</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>username<span class="token punctuation">"</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>$&#123;jdbc.username&#125;<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
                <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>property</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>password<span class="token punctuation">"</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>$&#123;jdbc.password&#125;<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>dataSource</span><span class="token punctuation">></span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>environment</span><span class="token punctuation">></span></span>

        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>environment</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>dev_oracle<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>transactionManager</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>JDBC<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>dataSource</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>POOLED<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
                <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>property</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>driver<span class="token punctuation">"</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>$&#123;orcl.driver&#125;<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
                <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>property</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>url<span class="token punctuation">"</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>$&#123;orcl.url&#125;<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
                <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>property</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>username<span class="token punctuation">"</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>$&#123;orcl.username&#125;<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
                <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>property</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>password<span class="token punctuation">"</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>$&#123;orcl.password&#125;<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>dataSource</span><span class="token punctuation">></span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>environment</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>environments</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></li>
<li><p><code>id</code>：指定当前环境的唯一标识 </p>
</li>
<li><p><code>transactionManager</code> 和 <code>dataSource</code> 都必须有</p>
</li>
</ul>
<h3 id="①-transactionManager"><a href="#①-transactionManager" class="headerlink" title="① transactionManager"></a>① transactionManager</h3><p><code> type</code>： JDBC | MANAGED | 自定义</p>
<ul>
<li><p>JDBC：使用了 JDBC 的提交和回滚设置，依赖于从数 据源得到的连接来管理事务范围。 JdbcTransactionFactory</p>
</li>
<li><p>MANAGED：不提交或回滚一个连接、让容器来管理 事务的整个生命周期（比如 JEE 应用服务器的上下 文）。 ManagedTransactionFactory </p>
</li>
<li><p>自定义：实现TransactionFactory接口，type=全类名/ 别名</p>
</li>
</ul>
<h3 id="②-dataSource"><a href="#②-dataSource" class="headerlink" title="② dataSource"></a>② dataSource</h3><p><code>type</code>： UNPOOLED | POOLED | JNDI | 自定义</p>
<ul>
<li>UNPOOLED：不使用连接池， UnpooledDataSourceFactory </li>
<li>POOLED：使用连接池， PooledDataSourceFactory</li>
<li>JNDI： 在EJB 或应用服务器这类容器中查找指定的数据源</li>
<li>自定义：实现DataSourceFactory接口，定义数据源的 获取方式。</li>
</ul>
<blockquote>
<p>实际开发中我们使用Spring管理数据源，并进行事务控制的配置来覆盖上述配置</p>
</blockquote>
<h2 id="7-databaseIdProvider-环境"><a href="#7-databaseIdProvider-环境" class="headerlink" title="7. databaseIdProvider 环境"></a>7. databaseIdProvider 环境</h2><p>MyBatis 可以根据不同的数据库厂商执行不同的语句。</p>
<p>databaseIdProvider：支持多数据库厂商的；</p>
<p><code>type=&quot;DB_VENDOR&quot;</code> ：VendorDatabaseIdProvider <strong>作用就是得到数据库厂商的标识</strong> (驱动getDatabaseProductName())，mybatis就能根据数据库厂商标识来执行不同的sql;</p>
<ul>
<li>MySQL</li>
<li>Oracle</li>
<li>SQL Server</li>
<li>。。。。。。</li>
</ul>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>databaseIdProvider</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>DB_VENDOR<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
	<span class="token comment">&lt;!-- 为不同的数据库厂商起别名 --></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>property</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>MySQL<span class="token punctuation">"</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>mysql<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>property</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>Oracle<span class="token punctuation">"</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>oracle<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>property</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>SQL Server<span class="token punctuation">"</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>sqlserver<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>databaseIdProvider</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token operator">&lt;</span>select id<span class="token operator">=</span><span class="token string">"getEmpById"</span> resultType<span class="token operator">=</span><span class="token string">"com.atguigu.mybatis.bean.Employee"</span><span class="token operator">></span>
	select <span class="token operator">*</span> from tbl_employee where id <span class="token operator">=</span> #<span class="token punctuation">&#123;</span>id<span class="token punctuation">&#125;</span>
<span class="token operator">&lt;</span><span class="token operator">/</span>select<span class="token operator">></span>

<span class="token operator">&lt;</span>select id<span class="token operator">=</span><span class="token string">"getEmpById"</span> resultType<span class="token operator">=</span><span class="token string">"com.atguigu.mybatis.bean.Employee"</span>
	databaseId<span class="token operator">=</span><span class="token string">"mysql"</span><span class="token operator">></span>
	select <span class="token operator">*</span> from tbl_employee where id <span class="token operator">=</span> #<span class="token punctuation">&#123;</span>id<span class="token punctuation">&#125;</span>
<span class="token operator">&lt;</span><span class="token operator">/</span>select<span class="token operator">></span>

<span class="token operator">&lt;</span>select id<span class="token operator">=</span><span class="token string">"getEmpById"</span> resultType<span class="token operator">=</span><span class="token string">"com.atguigu.mybatis.bean.Employee"</span>
	databaseId<span class="token operator">=</span><span class="token string">"oracle"</span><span class="token operator">></span>
	select <span class="token class-name">EMPLOYEE_ID</span> id<span class="token punctuation">,</span><span class="token class-name">LAST_NAME</span>	lastName<span class="token punctuation">,</span>EMAIL email 
	from employees where EMPLOYEE_ID<span class="token operator">=</span>#<span class="token punctuation">&#123;</span>id<span class="token punctuation">&#125;</span>
<span class="token operator">&lt;</span><span class="token operator">/</span>select<span class="token operator">></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>MyBatis 匹配规则如下：</p>
<ul>
<li><p><strong>如果没有配置 databaseIdProvider 标签，那么 databaseId=null</strong> </p>
</li>
<li><p>如果配置了databaseIdProvider 标签，使用标签配置的 name 去匹配数据库信息，匹配上设置databaseId = 配置指定的值，否则依旧为 null</p>
</li>
<li><p>如果 databaseId 不为null，他只会找到配置databaseId的sql语句</p>
</li>
<li><p>MyBatis 会加载不带 databaseId 属性和带有匹配当前数据库 databaseId 属性的所有语句。如果同时找到带有 databaseId 和不带 databaseId 的相同语句，则后者会被舍弃。</p>
</li>
</ul>
<h2 id="8-mapper-映射"><a href="#8-mapper-映射" class="headerlink" title="8. mapper 映射"></a>8. mapper 映射</h2><ul>
<li><p>mapper逐个注册SQL映射文件</p>
  <pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token comment">&lt;!-- mappers：将sql映射注册到全局配置中 --></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>mappers</span><span class="token punctuation">></span></span>
    <span class="token comment">&lt;!-- 
        mapper:注册一个sql映射 
            注册配置文件
            resource：引用类路径下的sql映射文件
                mybatis/mapper/EmployeeMapper.xml
            url：引用网路路径或者磁盘路径下的sql映射文件
                file:///var/mappers/AuthorMapper.xml
    --></span>

    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>mapper</span> <span class="token attr-name">resource</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>mybatis/mapper/EmployeeMapper.xml<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span> 

<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>mappers</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></li>
<li><p>⭐ 也可以采用 <strong>注册接口</strong> 的方法</p>
<p>  <code>class</code> ：引用（注册）接口，</p>
<p>  <strong>有 sql 映射文件，映射文件名必须和接口同名，并且放在与接口同一目录下；</strong></p>
  <pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>mapper</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.atguigu.mybatis.dao.EmployeeMapperAnnotation<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>  没有sql映射文件，所有的 sql 都是利用注解写在接口上;</p>
  <pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Select</span><span class="token punctuation">(</span><span class="token string">"select * from tbl_employee where id = #&#123;id&#125;"</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token class-name">Employee</span> <span class="token function">getEmeById</span><span class="token punctuation">(</span><span class="token class-name">Integer</span> id<span class="token punctuation">)</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>  推荐：</p>
<ul>
<li>比较重要的，复杂的 Dao 接口我们来写 sql 映射文件</li>
<li>不重要，简单的 Dao 接口为了开发快速可以使用注解；</li>
</ul>
</li>
<li><p>批量注册</p>
<p><strong>这种方式要求SQL映射文件名必须和接口名相同并且在同一目录下</strong></p>
  <pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>mappers</span><span class="token punctuation">></span></span>
<span class="token comment">&lt;!-- 批量注册： --></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>package</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.smallbeef.mybatis.dao<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>mappers</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre></li>
</ul>
<hr>
<h1 id="三、sql映射文件"><a href="#三、sql映射文件" class="headerlink" title="三、sql映射文件"></a>三、sql映射文件</h1><p> 映射文件指导着MyBatis如何进行数据库增删改查， 有着非常重要的意义；</p>
<ul>
<li>cache –命名空间的二级缓存配置</li>
<li>cache-ref – 其他命名空间缓存配置的引用</li>
<li>resultMap – 自定义结果集映射</li>
<li>parameterMap – 已废弃！老式风格的参数映射 </li>
<li>sql –抽取可重用语句块。 </li>
<li>insert – 映射插入语句 </li>
<li>update – 映射更新语句 </li>
<li>delete – 映射删除语句</li>
<li>select – 映射查询语句</li>
</ul>
<h2 id="1-增删改查-insert、update、delete、select"><a href="#1-增删改查-insert、update、delete、select" class="headerlink" title="1. 增删改查 insert、update、delete、select"></a>1. 增删改查 insert、update、delete、select</h2><p>查 <code>select</code> 元素在上面章节已经学习过了，接下来看 <code>insert</code>, <code>update</code>, <code>delete</code> 元素，在第一节代码的基础上完成一套完整的 CRUD 流程</p>
<p>mybatis 允许增删改直接定义以下类型返回值</p>
<ul>
<li>Integer</li>
<li>Long</li>
<li>Boolean</li>
<li>void</li>
</ul>
<p>Dao层接口类：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">EmployeeMapper</span> <span class="token punctuation">&#123;</span>

    <span class="token comment">/**
     * 查找
     * @param id
     * @return
     */</span>
    <span class="token keyword">public</span> <span class="token class-name">Employee</span> <span class="token function">getEmpById</span><span class="token punctuation">(</span><span class="token class-name">Integer</span> id<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token comment">/**
     * 更新
     * @param employee
     * @return
     */</span>
    <span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">updateEmp</span><span class="token punctuation">(</span><span class="token class-name">Employee</span> employee<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token comment">/**
     * 添加
     * @param employee
     * @return
     */</span>
    <span class="token keyword">public</span> <span class="token class-name">Integer</span> <span class="token function">addEmp</span><span class="token punctuation">(</span><span class="token class-name">Employee</span> employee<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token comment">/**
     * 删除
     * @param id
     */</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">deleteEmpById</span><span class="token punctuation">(</span><span class="token class-name">Integer</span> id<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<p>sql 映射文件：</p>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>mapper</span> <span class="token attr-name">namespace</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.smallbeef.mybatis.dao.EmployeeMapper<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
    <span class="token comment">&lt;!--id：唯一标识
    resultType: 返回值类型
    #&#123;id&#125;：从传递过来的参数中取出id值--></span>

    <span class="token comment">&lt;!--public Employee getEmpById(Integer id)
    将唯一标识id和接口中的方法进行绑定--></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>select</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>getEmpById<span class="token punctuation">"</span></span> <span class="token attr-name">resultType</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.smallbeef.mybatis.bean.Employee<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
        select id, last_name lastName, email, gender from tbl_employee where id = #&#123;id&#125;
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>select</span><span class="token punctuation">></span></span>

    <span class="token comment">&lt;!--public Integer addEmp(Employee employee);--></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>insert</span> <span class="token attr-name">id</span> <span class="token attr-value"><span class="token punctuation attr-equals">=</span> <span class="token punctuation">"</span>addEmp<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
        insert into tbl_employee(last_name, email, gender) values(#&#123;lastName&#125;, #&#123;email&#125;, #&#123;gender&#125;)
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>insert</span><span class="token punctuation">></span></span>

    <span class="token comment">&lt;!--public boolean updateEmp(Employee employee);--></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>update</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>updateEmp<span class="token punctuation">"</span></span> <span class="token punctuation">></span></span>
        update tbl_employee
        set last_name = #&#123;lastName&#125;, email = #&#123;email&#125;, gender = #&#123;gender&#125;
        where id = #&#123;id&#125;
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>update</span><span class="token punctuation">></span></span>

    <span class="token comment">&lt;!--public void deleteEmpById(Integer id);--></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>delete</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>deleteEmpById<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
        delete from tbl_employee
        where id = #&#123;id&#125;
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>delete</span><span class="token punctuation">></span></span>


<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>mapper</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<p>同时别忘了在 JavaBean 类中添加无参构造函数和构造函数，以及在全局配置文件中注册 sql 映射文件</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">/**
   * 测试增删改
   *   * 1、mybatis允许增删改直接定义以下类型返回值
   * 	 * 		Integer、Long、Boolean、void
   * 	 * 2、我们需要手动提交数据
   * 	 * 		sqlSessionFactory.openSession();===》手动提交
   * 	 * 		sqlSessionFactory.openSession(true);===》自动提交
   */</span>
  <span class="token annotation punctuation">@Test</span>
  <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test02</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span>  <span class="token class-name">IOException</span><span class="token punctuation">&#123;</span>
      <span class="token class-name">String</span> resource <span class="token operator">=</span> <span class="token string">"mybatis-config.xml"</span><span class="token punctuation">;</span>
      <span class="token class-name">InputStream</span> resourceAsStream <span class="token operator">=</span> <span class="token class-name">Resources</span><span class="token punctuation">.</span><span class="token function">getResourceAsStream</span><span class="token punctuation">(</span>resource<span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token class-name">SqlSessionFactory</span> sqlSessionFactory <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">SqlSessionFactoryBuilder</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">build</span><span class="token punctuation">(</span>resourceAsStream<span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token class-name">SqlSession</span> sqlSession <span class="token operator">=</span> sqlSessionFactory<span class="token punctuation">.</span><span class="token function">openSession</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token keyword">try</span><span class="token punctuation">&#123;</span>
          <span class="token class-name">EmployeeMapper</span> mapper <span class="token operator">=</span> sqlSession<span class="token punctuation">.</span><span class="token function">getMapper</span><span class="token punctuation">(</span><span class="token class-name">EmployeeMapper</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

          <span class="token comment">// 测试插入</span>
          <span class="token class-name">Employee</span> jack <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Employee</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">,</span> <span class="token string">"Jack"</span><span class="token punctuation">,</span> <span class="token string">"1"</span><span class="token punctuation">,</span> <span class="token string">"Jack@qq.com"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
          mapper<span class="token punctuation">.</span><span class="token function">addEmp</span><span class="token punctuation">(</span>jack<span class="token punctuation">)</span><span class="token punctuation">;</span>

          <span class="token comment">// 测试修改</span>
          <span class="token class-name">Employee</span> jack123 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Employee</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token string">"Jack123"</span><span class="token punctuation">,</span> <span class="token string">"0"</span><span class="token punctuation">,</span> <span class="token string">"Jack123@qq.com"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
          mapper<span class="token punctuation">.</span><span class="token function">updateEmp</span><span class="token punctuation">(</span>jack123<span class="token punctuation">)</span><span class="token punctuation">;</span>

          <span class="token comment">// 测试删除</span>
          mapper<span class="token punctuation">.</span><span class="token function">deleteEmpById</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

          <span class="token comment">//必须手动提交数据</span>
          sqlSession<span class="token punctuation">.</span><span class="token function">commit</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

      <span class="token punctuation">&#125;</span><span class="token keyword">finally</span> <span class="token punctuation">&#123;</span>
          sqlSession<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">&#125;</span>

  <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>注意一定要手动提交数据 <code>sqlSession.commit();</code></p>
<p>因为我们是这样打开的 <code>sqlSessionFactory.openSession();</code><br>可以通过 <code>sqlSessionFactory.openSession(true);</code> 来设置自动提交</p>
<h2 id="2-insert-获取自增主键的值"><a href="#2-insert-获取自增主键的值" class="headerlink" title="2. insert 获取自增主键的值"></a>2. insert 获取自增主键的值</h2><p>若数据库支持自动生成主键的字段（比如 MySQL 和 SQL Server），<br>则可以设置 <code>useGeneratedKeys=”true”</code>，然后再把 <code>keyProperty</code> 设置到目标属性上。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token operator">&lt;</span>insert id<span class="token operator">=</span><span class="token string">"addEmp"</span> parameterType<span class="token operator">=</span><span class="token string">"com.smallbeef.mybatis.bean.Employee"</span>
		useGeneratedKeys<span class="token operator">=</span><span class="token string">"true"</span> keyProperty<span class="token operator">=</span><span class="token string">"id"</span><span class="token operator">></span>
		insert into <span class="token function">tbl_employee</span><span class="token punctuation">(</span>last_name<span class="token punctuation">,</span>email<span class="token punctuation">,</span>gender<span class="token punctuation">)</span> 
		<span class="token function">values</span><span class="token punctuation">(</span>#<span class="token punctuation">&#123;</span>lastName<span class="token punctuation">&#125;</span><span class="token punctuation">,</span>#<span class="token punctuation">&#123;</span>email<span class="token punctuation">&#125;</span><span class="token punctuation">,</span>#<span class="token punctuation">&#123;</span>gender<span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
<span class="token operator">&lt;</span><span class="token operator">/</span>insert<span class="token operator">></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="3-参数处理"><a href="#3-参数处理" class="headerlink" title="3. 参数处理"></a>3. 参数处理</h2><h3 id="①-单个参数"><a href="#①-单个参数" class="headerlink" title="① 单个参数"></a>① 单个参数</h3><p>单个参数：mybatis不会做特殊处理，<code>#&#123;参数名/任意名&#125;：取出参数值</code></p>
<p>例如：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">Employee</span> <span class="token function">getEmpById</span><span class="token punctuation">(</span><span class="token class-name">Integer</span> id<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>不一定非要通过 <code>#&#123;id&#125;</code> 取出参数值，<strong>任意参数名都可取出</strong>，比如 <code>#&#123;abc&#125;</code></p>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>select</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>getEmpById<span class="token punctuation">"</span></span> <span class="token attr-name">resultType</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.smallbeef.mybatis.bean.Employee<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
		select * from tbl_employee where id = #&#123;abc&#125;
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>select</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<h3 id="②-多个参数"><a href="#②-多个参数" class="headerlink" title="② 多个参数"></a>② 多个参数</h3><p>多个参数的情况下，按照上面的方法取值会报错，比如：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">Employee</span> <span class="token function">getEmpByIdAndLastName</span><span class="token punctuation">(</span><span class="token class-name">Integer</span> id<span class="token punctuation">,</span><span class="token class-name">String</span> lastName<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">-</span>

<span class="token operator">&lt;</span>select id<span class="token operator">=</span><span class="token string">"getEmpByIdAndLastName"</span> resultType<span class="token operator">=</span><span class="token string">"com.smallbeef.mybatis.bean.Employee"</span><span class="token operator">></span>
 		select <span class="token operator">*</span> from tbl_employee where id <span class="token operator">=</span> #<span class="token punctuation">&#123;</span>id<span class="token punctuation">&#125;</span> and last_name<span class="token operator">=</span>#<span class="token punctuation">&#123;</span>lastName<span class="token punctuation">&#125;</span>
 <span class="token operator">&lt;</span><span class="token operator">/</span>select<span class="token operator">></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>报错如下：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>ibatis<span class="token punctuation">.</span>binding<span class="token punctuation">.</span></span>BindingException</span><span class="token operator">:</span> 
	<span class="token class-name">Parameter</span> <span class="token string">'id'</span> not <span class="token class-name"><span class="token namespace">found<span class="token punctuation">.</span></span> 
	Available</span> parameters are <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> param1<span class="token punctuation">,</span> param2<span class="token punctuation">]</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>任意多个参数，都会被 MyBatis 重新包装成一个Map传入。 </p>
<p>key：param1…paramN, 或者参数的索引也可以</p>
<p>value：传入的参数值</p>
<p><code>#&#123; &#125;</code> 就是从 map 中获取指定的 key 的值</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token operator">&lt;</span>select id<span class="token operator">=</span><span class="token string">"getEmpByIdAndLastName"</span> resultType<span class="token operator">=</span><span class="token string">"com.smallbeef.mybatis.bean.Employee"</span><span class="token operator">></span>
 		select <span class="token operator">*</span> from tbl_employee where id <span class="token operator">=</span> #<span class="token punctuation">&#123;</span>param1<span class="token punctuation">&#125;</span> and last_name<span class="token operator">=</span> #<span class="token punctuation">&#123;</span>param2<span class="token punctuation">&#125;</span>
<span class="token operator">&lt;</span><span class="token operator">/</span>select<span class="token operator">></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<h3 id="③-Param-命名参数"><a href="#③-Param-命名参数" class="headerlink" title="③ @Param 命名参数"></a>③ @Param 命名参数</h3><p>多个参数用上述这样的方法看起来不太直观，于是我们可以使用注解 <code>@Param</code> 为参数起一个名字，MyBatis就会将这些参数封装进 map 中，key 就是我们自己指定的名字 </p>
<p>举例如下：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">Employee</span> <span class="token function">getEmpByIdAndLastName</span><span class="token punctuation">(</span><span class="token annotation punctuation">@Param</span><span class="token punctuation">(</span><span class="token string">"id"</span><span class="token punctuation">)</span><span class="token class-name">Integer</span> id<span class="token punctuation">,</span><span class="token annotation punctuation">@Param</span><span class="token punctuation">(</span><span class="token string">"lastName"</span><span class="token punctuation">)</span><span class="token class-name">String</span> lastName<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">-</span>

<span class="token operator">&lt;</span>select id<span class="token operator">=</span><span class="token string">"getEmpByIdAndLastName"</span> resultType<span class="token operator">=</span><span class="token string">"com.smallbeef.mybatis.bean.Employee"</span><span class="token operator">></span>
 		select <span class="token operator">*</span> from tbl_employee where id <span class="token operator">=</span> #<span class="token punctuation">&#123;</span>id<span class="token punctuation">&#125;</span> and last_name <span class="token operator">=</span> #<span class="token punctuation">&#123;</span>lastName<span class="token punctuation">&#125;</span>
<span class="token operator">&lt;</span><span class="token operator">/</span>select<span class="token operator">></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="④-POJO"><a href="#④-POJO" class="headerlink" title="④ POJO"></a>④ POJO</h3><p>如果多个参数正好是我们业务逻辑的数据模型，我们就可以直接传入pojo；</p>
<p><code>#&#123;属性名&#125;</code>：取出传入的pojo的属性值    </p>
<p>举例如下：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">updateEmp</span><span class="token punctuation">(</span><span class="token class-name">Employee</span> employee<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">-</span>

<span class="token operator">&lt;</span>update id<span class="token operator">=</span><span class="token string">"updateEmp"</span><span class="token operator">></span>
		update tbl_employee 
		set last_name<span class="token operator">=</span>#<span class="token punctuation">&#123;</span>lastName<span class="token punctuation">&#125;</span><span class="token punctuation">,</span>email<span class="token operator">=</span>#<span class="token punctuation">&#123;</span>email<span class="token punctuation">&#125;</span><span class="token punctuation">,</span>gender<span class="token operator">=</span>#<span class="token punctuation">&#123;</span>gender<span class="token punctuation">&#125;</span>
		where id<span class="token operator">=</span>#<span class="token punctuation">&#123;</span>id<span class="token punctuation">&#125;</span>
<span class="token operator">&lt;</span><span class="token operator">/</span>update<span class="token operator">></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="⑤-Map"><a href="#⑤-Map" class="headerlink" title="⑤ Map"></a>⑤ Map</h3><p>如果多个参数不是业务模型中的数据，没有对应的pojo，不经常使用，为了方便，我们也可以封装多个参数为 map，直接传递</p>
<p><code>#&#123;key&#125;</code>：取出map中对应的值</p>
<p>举例如下：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">Employee</span> <span class="token function">getEmpByMap</span><span class="token punctuation">(</span><span class="token class-name">Map</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">Object</span><span class="token punctuation">></span></span> map<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">-</span>

<span class="token operator">&lt;</span>select id<span class="token operator">=</span><span class="token string">"getEmpByMap"</span> resultType<span class="token operator">=</span><span class="token string">"com.smallbeef.mybatis.bean.Employee"</span><span class="token operator">></span>
 		select <span class="token operator">*</span> from tbl_employee where id<span class="token operator">=</span>$<span class="token punctuation">&#123;</span>id<span class="token punctuation">&#125;</span> and last_name<span class="token operator">=</span>#<span class="token punctuation">&#123;</span>lastName<span class="token punctuation">&#125;</span>
<span class="token operator">&lt;</span><span class="token operator">/</span>select<span class="token operator">></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">EmployeeMapper</span> mapper <span class="token operator">=</span> openSession<span class="token punctuation">.</span><span class="token function">getMapper</span><span class="token punctuation">(</span><span class="token class-name">EmployeeMapper</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">//Employee employee = mapper.getEmpByIdAndLastName(1, "tom");</span>
<span class="token class-name">Map</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">Object</span><span class="token punctuation">></span></span> map <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">HashMap</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
map<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span><span class="token string">"id"</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
map<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span><span class="token string">"lastName"</span><span class="token punctuation">,</span> <span class="token string">"Tom"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">Employee</span> employee <span class="token operator">=</span> mapper<span class="token punctuation">.</span><span class="token function">getEmpByMap</span><span class="token punctuation">(</span>map<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="⑥-TO"><a href="#⑥-TO" class="headerlink" title="⑥ TO"></a>⑥ TO</h3><p>如果多个参数不是业务模型中的数据，但是经常要使用，推荐来编写一个 <code>TO（Transfer Object）</code> 数据传输对象</p>
<p>比如分页模型</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">Page</span><span class="token punctuation">&#123;</span>
	<span class="token keyword">int</span> index<span class="token punctuation">;</span>
	<span class="token keyword">int</span> size<span class="token punctuation">;</span>
	<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="参数处理综合示例"><a href="#参数处理综合示例" class="headerlink" title="参数处理综合示例"></a>参数处理综合示例</h3><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">Employee</span> <span class="token function">getEmp</span><span class="token punctuation">(</span><span class="token annotation punctuation">@Param</span><span class="token punctuation">(</span><span class="token string">"id"</span><span class="token punctuation">)</span><span class="token class-name">Integer</span> id<span class="token punctuation">,</span><span class="token class-name">String</span> lastName<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>取值：</p>
<ul>
<li>id —&gt; <code>#&#123;id / param1&#125;</code>   </li>
<li>lastName —&gt; <code>#&#123;param2&#125;</code></li>
</ul>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">Employee</span> <span class="token function">getEmp</span><span class="token punctuation">(</span><span class="token class-name">Integer</span> id<span class="token punctuation">,</span><span class="token annotation punctuation">@Param</span><span class="token punctuation">(</span><span class="token string">"e"</span><span class="token punctuation">)</span><span class="token class-name">Employee</span> emp<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>取值：</p>
<ul>
<li>id —&gt; <code>#&#123;param1&#125;</code></li>
<li>lastName —&gt; <code>#&#123;param2.lastName / e.lastName&#125;</code></li>
</ul>
<p><strong>特别注意：</strong></p>
<p>如果是Collection（List、Set）类型或者是数组，也会特殊处理。也是把传入的 list 或者数组封装在 map 中。</p>
<ul>
<li>Collection：则对应 key 为 collection</li>
<li>List：则对应 key 为 collection 或者 list</li>
</ul>
<p>举例如下：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">Employee</span> <span class="token function">getEmpById</span><span class="token punctuation">(</span><span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">></span></span> ids<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>取出第一个id的值：  <code> #&#123;list[0]&#125;</code></p>
<h3 id="参数处理-和-的区别"><a href="#参数处理-和-的区别" class="headerlink" title="参数处理 $ 和 # 的区别"></a>参数处理 $ 和 # 的区别</h3><ul>
<li><code>#&#123;&#125;</code> ：可以获取 map 中的值或者 pojo 对象属性的值；</li>
<li><code>$&#123;&#125;</code> ：可以获取 map 中的值或者 pojo 对象属性的值；</li>
</ul>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">select</span> <span class="token operator">*</span> <span class="token keyword">from</span> tbl_employee <span class="token keyword">where</span> id <span class="token operator">=</span> $&#123;id&#125; <span class="token operator">and</span> last_name<span class="token operator">=</span> <span class="token comment">#&#123;lastName&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>输出如下：</p>
<blockquote>
<p>Preparing: select * from tbl_employee where id=2 and last_name=?</p>
</blockquote>
<p>区别：</p>
<ul>
<li><p><code>#&#123;&#125;</code> : 是以预编译的形式，将参数设置到 sql 语句中，防止 sql 注入</p>
</li>
<li><p><code>$&#123;&#125;</code> : <strong>取出的值直接拼装在sql语句中；会有安全问题；</strong></p>
</li>
</ul>
<p>大多情况下，我们去参数的值都应该去使用 <code>#&#123;&#125;</code>；</p>
<p>原生jdbc不支持占位符的地方我们就可以使用 <code>$&#123;&#125; </code>进行取值<br>比如分表、排序。。。；</p>
<p>举例如下：</p>
<p>按照年份分表拆分</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">select</span> <span class="token operator">*</span> <span class="token keyword">from</span> $&#123;<span class="token keyword">year</span>&#125;_salary <span class="token keyword">where</span> xxx<span class="token punctuation">;</span>
<span class="token keyword">select</span> <span class="token operator">*</span> <span class="token keyword">from</span> tbl_employee <span class="token keyword">order</span> <span class="token keyword">by</span> $&#123;f_name&#125; $&#123;<span class="token keyword">order</span>&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<h2 id="3-select-元素"><a href="#3-select-元素" class="headerlink" title="3. select 元素"></a>3. select 元素</h2><p>Select 元素来定义查询操作。 </p>
<ul>
<li><code>Id</code>：唯一标识符。 — 用来引用这条语句，需要和接口的方法名一致</li>
<li><code>parameterType</code>：参数类型。 – 可以不传，MyBatis会根据TypeHandler自动推断</li>
<li><code>resultType</code>：返回值类型。 – 别名或者全类名，<strong>如果返回的是集合，定义集合中元 素的类型</strong>。不能和 resultMap 同时使用</li>
</ul>
<h3 id="①-resultType-返回值类型"><a href="#①-resultType-返回值类型" class="headerlink" title="① resultType 返回值类型"></a>① resultType 返回值类型</h3><h4 id="a-返回对象"><a href="#a-返回对象" class="headerlink" title="a. 返回对象"></a>a. 返回对象</h4><p>返回类型是对象的情况我们之前已经反复使用过了，下面来讲解以下其他返回类型</p>
<h4 id="b-返回-List"><a href="#b-返回-List" class="headerlink" title="b. 返回 List"></a>b. 返回 List</h4><p><strong>如果返回的是集合，resultType 中定义集合中的元素的类型</strong>，比如下面代码中的 Employee</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">></span></span> <span class="token function">getEmpsByLastNameLike</span><span class="token punctuation">(</span><span class="token class-name">String</span> lastName<span class="token punctuation">)</span><span class="token punctuation">;</span>
	
<span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span>

	<span class="token operator">&lt;</span><span class="token operator">!</span><span class="token operator">--</span>resultType：如果返回的是一个集合，要写集合中元素的类型  <span class="token operator">--</span><span class="token operator">></span>
	<span class="token operator">&lt;</span>select id<span class="token operator">=</span><span class="token string">"getEmpsByLastNameLike"</span> resultType<span class="token operator">=</span><span class="token string">"com.smallbeef.mybatis.bean.Employee"</span><span class="token operator">></span>
		select <span class="token operator">*</span> from tbl_employee where last_name like #<span class="token punctuation">&#123;</span>lastName<span class="token punctuation">&#125;</span>
	<span class="token operator">&lt;</span><span class="token operator">/</span>select<span class="token operator">></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>测试：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">></span></span> like <span class="token operator">=</span> mapper<span class="token punctuation">.</span><span class="token function">getEmpsByLastNameLike</span><span class="token punctuation">(</span><span class="token string">"%e%"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
			<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">Employee</span> employee <span class="token operator">:</span> like<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
				<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>employee<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="c-返回-Map"><a href="#c-返回-Map" class="headerlink" title="c. 返回 Map"></a>c. 返回 Map</h4><p><code>resultmap = &quot;map&quot;</code></p>
<h5 id="返回一条记录"><a href="#返回一条记录" class="headerlink" title="返回一条记录"></a>返回一条记录</h5><p>返回一条记录的 map；key就是列名，值就是对应的值</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">Map</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">Object</span><span class="token punctuation">></span></span> <span class="token function">getEmpByIdReturnMap</span><span class="token punctuation">(</span><span class="token class-name">Integer</span> id<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">-</span>

<span class="token operator">&lt;</span>select id<span class="token operator">=</span><span class="token string">"getEmpByIdReturnMap"</span> resultType<span class="token operator">=</span><span class="token string">"map"</span><span class="token operator">></span>
 		select <span class="token operator">*</span> from tbl_employee where id<span class="token operator">=</span>#<span class="token punctuation">&#123;</span>id<span class="token punctuation">&#125;</span>
<span class="token operator">&lt;</span><span class="token operator">/</span>select<span class="token operator">></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>测试：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">Map</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">Object</span><span class="token punctuation">></span></span> map <span class="token operator">=</span> mapper<span class="token punctuation">.</span><span class="token function">getEmpByIdReturnMap</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
			<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>map<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>


<p>结果：</p>
<blockquote>
<p>{id = 1, email=<a href="mailto:&#106;&#97;&#99;&#x6b;&#x40;&#113;&#x71;&#x2e;&#x63;&#x6f;&#109;">&#106;&#97;&#99;&#x6b;&#x40;&#113;&#x71;&#x2e;&#x63;&#x6f;&#109;</a>, last_name = Jack, gender = 0}</p>
</blockquote>
<h5 id="返回多条记录"><a href="#返回多条记录" class="headerlink" title="返回多条记录"></a>返回多条记录</h5><ul>
<li>多条记录封装一个map：<code>Map&lt;Integer,Employee&gt;</code> : 键是这条记录的主键，值是记录封装后的javaBean</li>
<li><code>@MapKey</code> : 告诉mybatis封装这个 map 的时候使用哪个属性作为 map 的 key</li>
</ul>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@MapKey</span><span class="token punctuation">(</span><span class="token string">"lastName"</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token class-name">Map</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">Employee</span><span class="token punctuation">></span></span> <span class="token function">getEmpByLastNameLikeReturnMap</span><span class="token punctuation">(</span><span class="token class-name">String</span> lastName<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">-</span>

<span class="token operator">&lt;</span>select id<span class="token operator">=</span><span class="token string">"getEmpByLastNameLikeReturnMap"</span> 	
	resultType<span class="token operator">=</span><span class="token string">"com.smallbeef.mybatis.bean.Employee"</span><span class="token operator">></span>
 		select <span class="token operator">*</span> from tbl_employee where last_name like #<span class="token punctuation">&#123;</span>lastName<span class="token punctuation">&#125;</span>
<span class="token operator">&lt;</span><span class="token operator">/</span>select<span class="token operator">></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>测试：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">Map</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">Employee</span><span class="token punctuation">></span></span> map <span class="token operator">=</span> mapper<span class="token punctuation">.</span><span class="token function">getEmpByLastNameLikeReturnMap</span><span class="token punctuation">(</span><span class="token string">"%r%"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
			<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>map<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>结果：</p>
<blockquote>
<p> {Jack = Employee[id = 1, lastName = Jack, email = <a href="mailto:&#106;&#x61;&#99;&#107;&#x40;&#x71;&#x71;&#46;&#99;&#111;&#109;">&#106;&#x61;&#99;&#107;&#x40;&#x71;&#x71;&#46;&#99;&#111;&#109;</a>, gender = 0],Tom = Employee[id = 2, lastName = Tom, email = <a href="mailto:&#x74;&#111;&#x6d;&#x40;&#113;&#x71;&#46;&#99;&#x6f;&#109;">&#x74;&#111;&#x6d;&#x40;&#113;&#x71;&#46;&#99;&#x6f;&#109;</a>, gender = 1]}</p>
</blockquote>
<h3 id="②-resultMap-自定义结果集映射规则"><a href="#②-resultMap-自定义结果集映射规则" class="headerlink" title="② resultMap 自定义结果集映射规则"></a>② resultMap 自定义结果集映射规则</h3><p><code>resultType</code> 自定义某个 JavaBean 的封装规则</p>
<p><strong>参数:</strong></p>
<ul>
<li>type：自定义规则的 JavaBean 类型</li>
<li>id: 唯一id方便引用</li>
</ul>
<p><strong>标签：</strong></p>
<ul>
<li>id ： 定义主键</li>
<li>result：定义其他普通键</li>
</ul>
<p><strong>标签属性：</strong></p>
<ul>
<li>column : 数据库表的列名</li>
<li>property : 对应的JavaBean属性</li>
</ul>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>resultMap</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.smallbeef.mybatis.bean.Employee<span class="token punctuation">"</span></span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>MySimpleEmp<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
	<span class="token comment">&lt;!--指定主键列的封装规则
	id 定义主键 底层会有优化；
		column：指定哪一列
		property：指定对应的javaBean属性
	result 定义普通列封装规则 
	 --></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>id</span> <span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>id<span class="token punctuation">"</span></span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>id<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
	
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>result</span> <span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>last_name<span class="token punctuation">"</span></span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>lastName<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
	<span class="token comment">&lt;!-- 其他不指定的列会自动封装：但是 推荐 我们只要写resultMap就把全部的映射规则都写上--></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>result</span> <span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>email<span class="token punctuation">"</span></span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>email<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>result</span> <span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>gender<span class="token punctuation">"</span></span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>gender<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>resultMap</span><span class="token punctuation">></span></span>

<span class="token comment">&lt;!-- resultMap:自定义结果集映射规则；  --></span>
<span class="token comment">&lt;!-- public Employee getEmpById(Integer id); --></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>select</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>getEmpById<span class="token punctuation">"</span></span>  <span class="token attr-name">resultMap</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>MySimpleEmp<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
	select * from tbl_employee where id=#&#123;id&#125;
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>select</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="③-resultMap-联合查询：级联属性封装结果集"><a href="#③-resultMap-联合查询：级联属性封装结果集" class="headerlink" title="③ resultMap 联合查询：级联属性封装结果集"></a>③ resultMap 联合查询：级联属性封装结果集</h3><ul>
<li>POJO 中的属性可能会是一个对象</li>
<li>我们可以使用联合查询，并以级联属性的方式封装对象。</li>
</ul>
<p>例如：员工表中含有部门对象</p>
<p>实体类：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Employee</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">private</span> <span class="token class-name">Integer</span> id<span class="token punctuation">;</span>
	<span class="token keyword">private</span> <span class="token class-name">String</span> lastName<span class="token punctuation">;</span>
	<span class="token keyword">private</span> <span class="token class-name">String</span> email<span class="token punctuation">;</span>
	<span class="token keyword">private</span> <span class="token class-name">String</span> gender<span class="token punctuation">;</span>
	<span class="token keyword">private</span> <span class="token class-name">Department</span> dept<span class="token punctuation">;</span>


<span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Department</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">private</span> <span class="token class-name">Integer</span> id<span class="token punctuation">;</span> <span class="token comment">//数据库表字段id</span>
	<span class="token keyword">private</span> <span class="token class-name">String</span> departmentName<span class="token punctuation">;</span> <span class="token comment">//数据库表字段dept_name</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>接口：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">Employee</span> <span class="token function">getEmpAndDept</span><span class="token punctuation">(</span><span class="token class-name">Integer</span> id<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>映射文件：</p>
<p>employee 中内嵌对象 dept 的属性通过 dept.id、dept.departmentName 等来获取</p>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token comment">&lt;!--
	联合查询：级联属性封装结果集
--></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>resultMap</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.smallbeef.mybatis.bean.Employee<span class="token punctuation">"</span></span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>MyDifEmp<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>id</span> <span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>id<span class="token punctuation">"</span></span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>id<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>result</span> <span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>last_name<span class="token punctuation">"</span></span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>lastName<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>result</span> <span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>gender<span class="token punctuation">"</span></span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>gender<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>result</span> <span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>did<span class="token punctuation">"</span></span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>dept.id<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>result</span> <span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>dept_name<span class="token punctuation">"</span></span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>dept.departmentName<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>resultMap</span><span class="token punctuation">></span></span>

<span class="token comment">&lt;!--  public Employee getEmpAndDept(Integer id);--></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>select</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>getEmpAndDept<span class="token punctuation">"</span></span> <span class="token attr-name">resultMap</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>MyDifEmp<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
		SELECT e.id id,e.last_name last_name,e.gender gender,e.d_id d_id,
		d.id did,d.dept_name dept_name FROM tbl_employee e,tbl_dept d
		WHERE e.d_id=d.id AND e.id=#&#123;id&#125;
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>select</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="④-resultMap-association：嵌套结果集"><a href="#④-resultMap-association：嵌套结果集" class="headerlink" title="④ resultMap association：嵌套结果集"></a>④ resultMap association：嵌套结果集</h3><p>使用association定义关联的单个对象的封装规则</p>
<p><code>association</code> 标签可以指定联合的 javaBean 对象</p>
<ul>
<li><code>property</code> = “dept” ：指定哪个属性是联合的对象</li>
<li><code>javaType</code> : 指定这个属性对象的类型[不能省略]</li>
</ul>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml">	<span class="token comment">&lt;!-- 
		使用association定义关联的单个对象的封装规则；
	 --></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>resultMap</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.smallbeef.mybatis.bean.Employee<span class="token punctuation">"</span></span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>MyDifEmp2<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>id</span> <span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>id<span class="token punctuation">"</span></span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>id<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>result</span> <span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>last_name<span class="token punctuation">"</span></span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>lastName<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>result</span> <span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>gender<span class="token punctuation">"</span></span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>gender<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
		
		<span class="token comment">&lt;!--  association可以指定联合的javaBean对象
		property="dept"：指定哪个属性是联合的对象
		javaType:指定这个属性对象的类型[不能省略]
		--></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>association</span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>dept<span class="token punctuation">"</span></span> <span class="token attr-name">javaType</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.smallbeef.mybatis.bean.Department<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>id</span> <span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>did<span class="token punctuation">"</span></span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>id<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>result</span> <span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>dept_name<span class="token punctuation">"</span></span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>departmentName<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>association</span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>resultMap</span><span class="token punctuation">></span></span>

<span class="token comment">&lt;!--  public Employee getEmpAndDept(Integer id);--></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>select</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>getEmpAndDept<span class="token punctuation">"</span></span> <span class="token attr-name">resultMap</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>MyDifEmp2<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
		SELECT e.id id,e.last_name last_name,e.gender gender,e.d_id d_id,
		d.id did,d.dept_name dept_name FROM tbl_employee e,tbl_dept d
		WHERE e.d_id=d.id AND e.id=#&#123;id&#125;
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>select</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="⑤-resultMap-association：分步查询"><a href="#⑤-resultMap-association：分步查询" class="headerlink" title="⑤ resultMap association：分步查询"></a>⑤ resultMap association：分步查询</h3><p>使用 <code>association</code> 进行分步查询：</p>
<ul>
<li><p>先按照员工 id 查询员工信息</p>
  <pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">select</span> <span class="token operator">*</span> <span class="token keyword">from</span> tbl_employee <span class="token keyword">where</span> id <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre></li>
<li><p>根据查询到的员工信息中的 d_id 值去部门表查出部门信息</p>
  <pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">select</span> <span class="token operator">*</span> <span class="token keyword">from</span> tbl_dept <span class="token keyword">where</span> id <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre></li>
<li><p>将部门信息设置到员工中；</p>
</li>
</ul>
<p><strong>association 标签的相关属性</strong></p>
<ul>
<li><code>select</code> : 表明当前属性是调用 select 指定的方法查出的结果</li>
<li><code>column</code> : 指定将哪一列的值传给这个方法</li>
</ul>
<p><strong>流程</strong> ：使用 select 指定的方法（传入column 指定的这列参数的值）查出对象，并封装给 property 指定的属性</p>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token comment">&lt;!--  id  last_name  email   gender    d_id   --></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>resultMap</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.smallbeef.mybatis.bean.Employee<span class="token punctuation">"</span></span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>MyEmpByStep<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
	 	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>id</span> <span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>id<span class="token punctuation">"</span></span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>id<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
	 	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>result</span> <span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>last_name<span class="token punctuation">"</span></span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>lastName<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
	 	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>result</span> <span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>email<span class="token punctuation">"</span></span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>email<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
	 	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>result</span> <span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>gender<span class="token punctuation">"</span></span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>gender<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
	 	<span class="token comment">&lt;!-- association定义关联对象的封装规则
	 		select:表明当前属性是调用select指定的方法查出的结果
	 		column:指定将哪一列的值传给这个方法
	 		
	 		流程：使用select指定的方法（传入column指定的这列参数的值）查出对象，并封装给property指定的属性
	 	 --></span>
 		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>association</span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>dept<span class="token punctuation">"</span></span> 
	 		<span class="token attr-name">select</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.smallbeef.mybatis.dao.DepartmentMapper.getDeptById<span class="token punctuation">"</span></span>
	 		<span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>d_id<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
 		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>association</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>resultMap</span><span class="token punctuation">></span></span>
	 
<span class="token comment">&lt;!--  public Employee getEmpByIdStep(Integer id);--></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>select</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>getEmpByIdStep<span class="token punctuation">"</span></span> <span class="token attr-name">resultMap</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>MyEmpByStep<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
	 select * from tbl_employee where id=#&#123;id&#125;
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>select</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<img src="https://gitee.com/veal98/images/raw/master/img/20200523214039.png" style="zoom: 67%;" />



<p>其中，根据部门 id 查询部门信息 getDeptById 如下：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">Department</span> <span class="token function">getDeptByIdStep</span><span class="token punctuation">(</span><span class="token class-name">Integer</span> id<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">-</span>

<span class="token operator">&lt;</span>select id<span class="token operator">=</span><span class="token string">"getDeptById"</span> resultType<span class="token operator">=</span><span class="token string">"com.smallbeef.mybatis.bean.Department"</span><span class="token operator">></span>
		select id<span class="token punctuation">,</span>dept_name departmentName from tbl_dept where id<span class="token operator">=</span>#<span class="token punctuation">&#123;</span>id<span class="token punctuation">&#125;</span>
	<span class="token operator">&lt;</span><span class="token operator">/</span>select<span class="token operator">></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="⑥-resultMap-association：分步查询-amp-延迟加载"><a href="#⑥-resultMap-association：分步查询-amp-延迟加载" class="headerlink" title="⑥ resultMap association：分步查询 &amp; 延迟加载"></a>⑥ resultMap association：分步查询 &amp; 延迟加载</h3><p>在分步查询基础上实现延迟加载（懒加载）</p>
<p>在全局配置文件中开启延迟加载和属性按需加载</p>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>settings</span><span class="token punctuation">></span></span>	
		<span class="token comment">&lt;!--显示的指定每个我们需要更改的配置的值，即使他是默认的。防止版本更新带来的问题  --></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>setting</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>lazyLoadingEnabled<span class="token punctuation">"</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>true<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>setting</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>aggressiveLazyLoading<span class="token punctuation">"</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>false<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>settings</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="⑦-resultMap-collection：嵌套结果集"><a href="#⑦-resultMap-collection：嵌套结果集" class="headerlink" title="⑦ resultMap collection：嵌套结果集"></a>⑦ resultMap collection：嵌套结果集</h3><p>场景：查询部门的时候将部门对应的所有员工信息也查询出来</p>
<p>部门表对应的JavaBean，内嵌员工信息的集合属性</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Department</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">private</span> <span class="token class-name">Integer</span> id<span class="token punctuation">;</span>
	<span class="token keyword">private</span> <span class="token class-name">String</span> departmentName<span class="token punctuation">;</span>
	<span class="token keyword">private</span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">></span></span> emps<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">></span></span> <span class="token function">getEmpsByDeptId</span><span class="token punctuation">(</span><span class="token class-name">Integer</span> deptId<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span>

	<span class="token operator">&lt;</span>select id<span class="token operator">=</span><span class="token string">"getEmpsByDeptId"</span> resultType<span class="token operator">=</span><span class="token string">"com.smallbeef.mybatis.bean.Employee"</span><span class="token operator">></span>
		select <span class="token operator">*</span> from tbl_employee where d_id<span class="token operator">=</span> #<span class="token punctuation">&#123;</span>deptId<span class="token punctuation">&#125;</span>
	<span class="token operator">&lt;</span><span class="token operator">/</span>select<span class="token operator">></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><code>collection</code> 标签定义关联集合类型的属性的封装规则 </p>
<p><strong>参数：</strong></p>
<ul>
<li><code>property</code> ：指定要封装到哪个集合属性（本例中封装到部门对象中的 emps 属性）</li>
<li><code>ofType</code> : 指定集合里面元素的类型</li>
</ul>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token operator">&lt;</span><span class="token operator">!</span><span class="token operator">--</span>嵌套结果集的方式，使用collection标签定义关联的集合类型的属性封装规则  <span class="token operator">--</span><span class="token operator">></span>
	<span class="token operator">&lt;</span>resultMap type<span class="token operator">=</span><span class="token string">"com.smallbeef.mybatis.bean.Department"</span> id<span class="token operator">=</span><span class="token string">"MyDept"</span><span class="token operator">></span>
		<span class="token operator">&lt;</span>id column<span class="token operator">=</span><span class="token string">"did"</span> property<span class="token operator">=</span><span class="token string">"id"</span><span class="token operator">/</span><span class="token operator">></span>
		<span class="token operator">&lt;</span>result column<span class="token operator">=</span><span class="token string">"dept_name"</span> property<span class="token operator">=</span><span class="token string">"departmentName"</span><span class="token operator">/</span><span class="token operator">></span>
		<span class="token operator">&lt;</span><span class="token operator">!</span><span class="token operator">--</span> 
			collection定义关联集合类型的属性的封装规则 
			ofType<span class="token operator">:</span>指定集合里面元素的类型
		<span class="token operator">--</span><span class="token operator">></span>
		<span class="token operator">&lt;</span>collection property<span class="token operator">=</span><span class="token string">"emps"</span> ofType<span class="token operator">=</span><span class="token string">"com.smallbeef.mybatis.bean.Employee"</span><span class="token operator">></span>
			<span class="token operator">&lt;</span><span class="token operator">!</span><span class="token operator">--</span> 定义这个集合中元素的封装规则 <span class="token operator">--</span><span class="token operator">></span>
			<span class="token operator">&lt;</span>id column<span class="token operator">=</span><span class="token string">"eid"</span> property<span class="token operator">=</span><span class="token string">"id"</span><span class="token operator">/</span><span class="token operator">></span>
			<span class="token operator">&lt;</span>result column<span class="token operator">=</span><span class="token string">"last_name"</span> property<span class="token operator">=</span><span class="token string">"lastName"</span><span class="token operator">/</span><span class="token operator">></span>
			<span class="token operator">&lt;</span>result column<span class="token operator">=</span><span class="token string">"email"</span> property<span class="token operator">=</span><span class="token string">"email"</span><span class="token operator">/</span><span class="token operator">></span>
			<span class="token operator">&lt;</span>result column<span class="token operator">=</span><span class="token string">"gender"</span> property<span class="token operator">=</span><span class="token string">"gender"</span><span class="token operator">/</span><span class="token operator">></span>
		<span class="token operator">&lt;</span><span class="token operator">/</span>collection<span class="token operator">></span>
	<span class="token operator">&lt;</span><span class="token operator">/</span>resultMap<span class="token operator">></span>


	<span class="token operator">&lt;</span><span class="token operator">!</span><span class="token operator">--</span> <span class="token keyword">public</span> <span class="token class-name">Department</span> <span class="token function">getDeptByIdPlus</span><span class="token punctuation">(</span><span class="token class-name">Integer</span> id<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token operator">--</span><span class="token operator">></span>
	<span class="token operator">&lt;</span>select id<span class="token operator">=</span><span class="token string">"getDeptByIdPlus"</span> resultMap<span class="token operator">=</span><span class="token string">"MyDept"</span><span class="token operator">></span>
		SELECT d<span class="token punctuation">.</span>id did<span class="token punctuation">,</span>d<span class="token punctuation">.</span>dept_name dept_name<span class="token punctuation">,</span>
				e<span class="token punctuation">.</span>id eid<span class="token punctuation">,</span>e<span class="token punctuation">.</span>last_name last_name<span class="token punctuation">,</span>e<span class="token punctuation">.</span>email email<span class="token punctuation">,</span>e<span class="token punctuation">.</span>gender gender
		FROM tbl_dept d
		LEFT JOIN tbl_employee e
		ON d<span class="token punctuation">.</span>id<span class="token operator">=</span>e<span class="token punctuation">.</span>d_id
		WHERE d<span class="token punctuation">.</span>id<span class="token operator">=</span>#<span class="token punctuation">&#123;</span>id<span class="token punctuation">&#125;</span>
	<span class="token operator">&lt;</span><span class="token operator">/</span>select<span class="token operator">></span>
	<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="⑧-resultMap-collection：分步查询"><a href="#⑧-resultMap-collection：分步查询" class="headerlink" title="⑧ resultMap collection：分步查询"></a>⑧ resultMap collection：分步查询</h3><p>需求：根据部门 id 查询该部门下所有的员工信息</p>
<ul>
<li>根据部门 id 查询部门信息</li>
<li>根据部门 id 查询员工信息</li>
</ul>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token comment">&lt;!-- collection：分段查询 --></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>resultMap</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.smallbeef.mybatis.bean.Department<span class="token punctuation">"</span></span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>MyDeptStep<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>id</span> <span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>id<span class="token punctuation">"</span></span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>id<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>id</span> <span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>dept_name<span class="token punctuation">"</span></span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>departmentName<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>collection</span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>emps<span class="token punctuation">"</span></span> 
		<span class="token attr-name">select</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.smallbeef.mybatis.dao.EmployeeMapperPlus.getEmpsByDeptId<span class="token punctuation">"</span></span>
		<span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>id<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>collection</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>resultMap</span><span class="token punctuation">></span></span>


<span class="token comment">&lt;!-- public Department getDeptByIdStep(Integer id); --></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>select</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>getDeptByIdStep<span class="token punctuation">"</span></span> <span class="token attr-name">resultMap</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>MyDeptStep<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
	select id,dept_name from tbl_dept where id=#&#123;id&#125;
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>select</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>其中根据部门id查询员工信息 getEmpsByDeptId</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">></span></span> <span class="token function">getEmpsByDeptId</span><span class="token punctuation">(</span><span class="token class-name">Integer</span> deptId<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">-</span>

	<span class="token operator">&lt;</span>select id<span class="token operator">=</span><span class="token string">"getEmpsByDeptId"</span> resultType<span class="token operator">=</span><span class="token string">"com.smallbeef.mybatis.bean.Employee"</span><span class="token operator">></span>
		select <span class="token operator">*</span> from tbl_employee where d_id<span class="token operator">=</span>#<span class="token punctuation">&#123;</span>deptId<span class="token punctuation">&#125;</span>
	<span class="token operator">&lt;</span><span class="token operator">/</span>select<span class="token operator">></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="⑨-resultMap-collection：多列值封装map-amp-懒加载"><a href="#⑨-resultMap-collection：多列值封装map-amp-懒加载" class="headerlink" title="⑨ resultMap collection：多列值封装map &amp; 懒加载"></a>⑨ resultMap collection：多列值封装map &amp; 懒加载</h3><p>分步查询的时候通过column指定，将对应的列的数据传递过去，我们有时需要传递多列数据 ：将多列的值封装 map 传递；</p>
<p><code>column=&quot;&#123;key1=column1,key2=column2&#125;&quot;</code></p>
<p>key是方法中的形参，column是数据库表列名</p>
<br>

<p><code>fetchType=&quot;lazy&quot;</code> ：表示使用延迟加载，该标签可以覆盖全局的延迟加载策略</p>
<ul>
<li>lazy：延迟</li>
<li>eager：立即</li>
</ul>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token operator">&lt;</span>resultMap type<span class="token operator">=</span><span class="token string">"com.smallbeef.mybatis.bean.Department"</span> id<span class="token operator">=</span><span class="token string">"MyDeptStep"</span><span class="token operator">></span>
		<span class="token operator">&lt;</span>id column<span class="token operator">=</span><span class="token string">"id"</span> property<span class="token operator">=</span><span class="token string">"id"</span><span class="token operator">/</span><span class="token operator">></span>
		<span class="token operator">&lt;</span>id column<span class="token operator">=</span><span class="token string">"dept_name"</span> property<span class="token operator">=</span><span class="token string">"departmentName"</span><span class="token operator">/</span><span class="token operator">></span>
		<span class="token operator">&lt;</span>collection property<span class="token operator">=</span><span class="token string">"emps"</span> 
			select<span class="token operator">=</span><span class="token string">"com.smallbeef.mybatis.dao.EmployeeMapperPlus.getEmpsByDeptId"</span>
			column<span class="token operator">=</span><span class="token string">"&#123;deptId=id&#125;"</span> fetchType<span class="token operator">=</span><span class="token string">"lazy"</span><span class="token operator">></span><span class="token operator">&lt;</span><span class="token operator">/</span>collection<span class="token operator">></span>
<span class="token operator">&lt;</span><span class="token operator">/</span>resultMap<span class="token operator">></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="⑩-resultMap-discriminator-鉴别器"><a href="#⑩-resultMap-discriminator-鉴别器" class="headerlink" title="⑩ resultMap discriminator 鉴别器"></a>⑩ resultMap discriminator 鉴别器</h3><p>鉴别器：mybatis可以使用 <code>discriminator</code> 判断某列的值，然后根据某列的值改变封装行为</p>
<p><code>&lt;discriminator javaType=&quot; &quot; column = &quot; &quot;&gt;&lt;/discriminator&gt;</code></p>
<p><strong>属性：</strong></p>
<ul>
<li>column：指定判定的列名</li>
<li>javaType：列值对应的java类型  </li>
</ul>
<p>场景：</p>
<ul>
<li>如果查出的是女生：就把部门信息查询出来，否则不查询；</li>
<li>如果是男生，把 last_name 这一列的值赋值给  email;</li>
</ul>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>resultMap</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.smallbeef.mybatis.bean.Employee<span class="token punctuation">"</span></span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>MyEmpDis<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>id</span> <span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>id<span class="token punctuation">"</span></span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>id<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>result</span> <span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>last_name<span class="token punctuation">"</span></span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>lastName<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>result</span> <span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>email<span class="token punctuation">"</span></span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>email<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>result</span> <span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>gender<span class="token punctuation">"</span></span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>gender<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
	<span class="token comment">&lt;!--
		column：指定判定的列名
		javaType：列值对应的java类型  --></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>discriminator</span> <span class="token attr-name">javaType</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>String<span class="token punctuation">"</span></span> <span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>gender<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
		<span class="token comment">&lt;!--女生  resultType:指定封装的结果类型；不能缺少--></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>case</span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>0<span class="token punctuation">"</span></span> <span class="token attr-name">resultType</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.smallbeef.mybatis.bean.Employee<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>association</span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>dept<span class="token punctuation">"</span></span> 
	 		<span class="token attr-name">select</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.smallbeef.mybatis.dao.DepartmentMapper.getDeptById<span class="token punctuation">"</span></span>
	 		<span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>d_id<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
 		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>association</span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>case</span><span class="token punctuation">></span></span>
		<span class="token comment">&lt;!--男生 ;如果是男生，把last_name这一列的值赋值给email; --></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>case</span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>1<span class="token punctuation">"</span></span> <span class="token attr-name">resultType</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.smallbeef.mybatis.bean.Employee<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
 		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>id</span> <span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>id<span class="token punctuation">"</span></span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>id<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
	 	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>result</span> <span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>last_name<span class="token punctuation">"</span></span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>lastName<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
	 	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>result</span> <span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>last_name<span class="token punctuation">"</span></span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>email<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
	 	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>result</span> <span class="token attr-name">column</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>gender<span class="token punctuation">"</span></span> <span class="token attr-name">property</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>gender<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>case</span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>discriminator</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>resultMap</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<hr>
<h1 id="四、动态-SQL"><a href="#四、动态-SQL" class="headerlink" title="四、动态 SQL"></a>四、动态 SQL</h1><p>动态 SQL是MyBatis强大特性之一。极大的简化我们拼装 SQL的操作。 动态 SQL 元素和使用 JSTL 或其他类似基于 XML 的文本处 理器相似。MyBatis 采用功能强大的基于 <code>OGNL</code> 的表达式来简化操作。 </p>
<ul>
<li>if  判断</li>
<li>choose (when, otherwise) 分支选择</li>
<li> trim (where, set)  字符串截取</li>
<li>foreach 遍历集合</li>
</ul>
<h2 id="1-if-判断-amp-OGNL-判断表达式"><a href="#1-if-判断-amp-OGNL-判断表达式" class="headerlink" title="1. if 判断 &amp; OGNL 判断表达式"></a>1. if 判断 &amp; OGNL 判断表达式</h2><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">></span></span> <span class="token function">getEmpsByConditionIf</span><span class="token punctuation">(</span><span class="token class-name">Employee</span> employee<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>查询员工，要求：携带了哪个字段查询条件就带上这个字段的值</p>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token comment">&lt;!-- public List&lt;Employee> getEmpsByConditionIf(Employee employee); --></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>select</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>getEmpsByConditionIf<span class="token punctuation">"</span></span> <span class="token attr-name">resultType</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.smallbeef.mybatis.bean.Employee<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
	select * from tbl_employee where
 	<span class="token comment">&lt;!-- test：判断表达式（OGNL）从参数中取值进行判断 --></span>
 	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>id!=null<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
 		id=#&#123;id&#125;
 	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span>
 	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>lastName!=null and lastName!=<span class="token punctuation">'</span><span class="token punctuation">'</span><span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
 		and last_name like #&#123;lastName&#125;
 	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span>
 	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>email!=null and email.trim()!=<span class="token punctuation">'</span><span class="token punctuation">'</span><span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
 		and email=#&#123;email&#125;
 	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span> 
 	<span class="token comment">&lt;!-- ognl会进行字符串与数字的转换判断  "0"==0 --></span>
 	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>gender==0 or gender==1<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
 	 	and gender=#&#123;gender&#125;
 	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>select</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>如果查询字段email为空</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">Employee</span> employee <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Employee</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token string">"Admin"</span><span class="token punctuation">,</span> <span class="token keyword">null</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">></span></span> emps <span class="token operator">=</span> mapper<span class="token punctuation">.</span><span class="token function">getEmpsByConditionIf</span><span class="token punctuation">(</span>employee <span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>则查询语句为 </p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">select</span> <span class="token operator">*</span> <span class="token keyword">from</span> tbl_employee <span class="token keyword">where</span> id <span class="token operator">=</span> ? <span class="token operator">and</span> last_name <span class="token operator">=</span> ? <span class="token operator">and</span> gender <span class="token operator">=</span> ?<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<h2 id="2-where-查询条件"><a href="#2-where-查询条件" class="headerlink" title="2. where 查询条件"></a>2. where 查询条件</h2><p>上述写法我们可以看见一个问题，如果 id = null，那么查询语句就变成</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">select</span> <span class="token operator">*</span> <span class="token keyword">from</span> tbl_employee <span class="token keyword">where</span> <span class="token operator">and</span> last_name <span class="token operator">=</span> ? <span class="token operator">and</span> gender <span class="token operator">=</span> ?<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>语法出错，and 被强行拼接，解决方法有两种：</p>
<ul>
<li><p>👍 在 <code>selet * from table_name</code> 后面加上 <code>where 1 = 1</code>，并在所有的条件语句都加上and前缀</p>
<p>则如果 id = null，那么查询语句任然成立</p>
  <pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token comment">&lt;!-- public List&lt;Employee> getEmpsByConditionIf(Employee employee); --></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>select</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>getEmpsByConditionIf<span class="token punctuation">"</span></span> <span class="token attr-name">resultType</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.smallbeef.mybatis.bean.Employee<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
   select * from tbl_employee where 1 = 1
       <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>id!=null<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
           and id=#&#123;id&#125;
       <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span>
       <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>lastName!=null and lastName!=<span class="token punctuation">'</span><span class="token punctuation">'</span><span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
           and last_name like #&#123;lastName&#125;
       <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span>
       <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>email!=null and email.trim()!=<span class="token punctuation">'</span><span class="token punctuation">'</span><span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
           and email=#&#123;email&#125;
       <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span> 
       <span class="token comment">&lt;!-- ognl会进行字符串与数字的转换判断  "0"==0 --></span>
       <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>gender==0 or gender==1<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
           and gender=#&#123;gender&#125;
       <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>select</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">select</span> <span class="token operator">*</span> <span class="token keyword">from</span> tbl_employee <span class="token keyword">where</span> <span class="token number">1</span> <span class="token operator">=</span> <span class="token number">1</span> <span class="token operator">and</span> last_name <span class="token operator">=</span> ? <span class="token operator">and</span> gender <span class="token operator">=</span> ?<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre></li>
<li><p>将 if 判断语句全都写在 <code>where</code> 标签中</p>
  <pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>select</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>getEmpsByConditionIf<span class="token punctuation">"</span></span> <span class="token attr-name">resultType</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.smallbeef.mybatis.bean.Employee<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
        select * from tbl_employee
        <span class="token comment">&lt;!-- where --></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>where</span><span class="token punctuation">></span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>id!=null<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
                and id=#&#123;id&#125;
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>lastName!=null and lastName!= <span class="token punctuation">'</span><span class="token punctuation">'</span><span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
                and last_name like #&#123;lastName&#125;
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>email!=null and email.trim()!= <span class="token punctuation">'</span><span class="token punctuation">'</span><span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
                and email=#&#123;email&#125;
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span> 
            <span class="token comment">&lt;!-- ognl会进行字符串与数字的转换判断  "0"==0 --></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>gender==0 or gender==1<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
                and gender=#&#123;gender&#125;
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>where</span><span class="token punctuation">></span></span>
     <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>select</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>  where 会自动剔除多出来的 <strong>第一个前缀</strong> and 或者 or</p>
<p>  可以看见，上述的做法依然存在漏洞，如果我们的写法是把and放在后面：</p>
</li>
</ul>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>select</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>getEmpsByConditionIf<span class="token punctuation">"</span></span> <span class="token attr-name">resultType</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.smallbeef.mybatis.bean.Employee<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
        select * from tbl_employee
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>where</span><span class="token punctuation">></span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>id!=null<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
                id=#&#123;id&#125; and 
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>lastName!=null and lastName!= <span class="token punctuation">'</span><span class="token punctuation">'</span><span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
                last_name like #&#123;lastName&#125; and 
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>email!=null and email.trim()!= <span class="token punctuation">'</span><span class="token punctuation">'</span><span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
                email=#&#123;email&#125; and 
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span> 
            <span class="token comment">&lt;!-- ognl会进行字符串与数字的转换判断  "0"==0 --></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>gender==0 or gender==1<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
                gender=#&#123;gender&#125;
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>where</span><span class="token punctuation">></span></span>
     <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>select</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>如果 gender 为空，则查询语句为</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">select</span> <span class="token operator">*</span> <span class="token keyword">from</span> tbl_employee id <span class="token operator">=</span> ? <span class="token operator">and</span> last_name <span class="token operator">=</span> ? <span class="token operator">and</span> email <span class="token operator">=</span> ? <span class="token operator">and</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>语法出错，因为 where 只能剔除多出来的 <strong>第一个前缀</strong> and 或者 or</p>
<p>所以，<strong>在使用 where 标签的时候，建议把 and 写在语句的前面</strong></p>
<h2 id="3-trim-自定义字符串截取"><a href="#3-trim-自定义字符串截取" class="headerlink" title="3. trim 自定义字符串截取"></a>3. trim 自定义字符串截取</h2><p>对于上述把 and 写在后面的写法，我们可以使用 <code>trim</code> 标签 自定义字符串的截取规则 </p>
<p>trim 标签中的属性：</p>
<ul>
<li><code>prefix=&quot;&quot;</code> 前缀：trim标签体中是整个字符串拼串后的结果  prefix 给拼串后的整个字符串加一个前缀 </li>
<li><code>prefixOverrides=&quot;&quot;</code> 前缀覆盖： 去掉整个字符串前面多余的字符</li>
<li><code>suffix=&quot;&quot;</code> 后缀：suffix给拼串后的整个字符串加一个后缀 </li>
<li><code>suffixOverrides=&quot;&quot;</code> 后缀覆盖：去掉整个字符串后面多余的字符</li>
</ul>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>select</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>getEmpsByConditionTrim<span class="token punctuation">"</span></span> <span class="token attr-name">resultType</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.smallbeef.mybatis.bean.Employee<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
	 	select * from tbl_employee
	 	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>trim</span> <span class="token attr-name">prefix</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>where<span class="token punctuation">"</span></span> <span class="token attr-name">suffixOverrides</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>and<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
	 		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>id!=null<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
		 		id=#&#123;id&#125; and
		 	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span>
		 	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>lastName!=null <span class="token entity named-entity" title="&amp;">&amp;amp;</span><span class="token entity named-entity" title="&amp;">&amp;amp;</span> lastName!=<span class="token entity named-entity" title="&quot;">&amp;quot;</span><span class="token entity named-entity" title="&quot;">&amp;quot;</span><span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
		 		last_name like #&#123;lastName&#125; and
		 	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span>
		 	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>email!=null and email.trim()!=<span class="token entity named-entity" title="&quot;">&amp;quot;</span><span class="token entity named-entity" title="&quot;">&amp;quot;</span><span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
		 		email=#&#123;email&#125; and
		 	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span> 
		 	<span class="token comment">&lt;!-- ognl会进行字符串与数字的转换判断  "0"==0 --></span>
		 	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>gender==0 or gender==1<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
		 	 	gender=#&#123;gender&#125;
		 	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span>
		 <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>trim</span><span class="token punctuation">></span></span>
	 <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>select</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="4-choose-分支选择"><a href="#4-choose-分支选择" class="headerlink" title="4. choose 分支选择"></a>4. choose 分支选择</h2><p><code>choose (when, otherwise):</code> 分支选择；</p>
<p><strong>等同于 带了 break 的 swtich-case</strong></p>
<p>如果带了 id 就用 id 查，如果带了 lastName 就用 lastName 查 ; <u>只会进入其中一个查询语句</u></p>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>select</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>getEmpsByConditionChoose<span class="token punctuation">"</span></span> <span class="token attr-name">resultType</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.smallbeef.mybatis.bean.Employee<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
 	select * from tbl_employee 
 	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>where</span><span class="token punctuation">></span></span>
 		<span class="token comment">&lt;!-- 如果带了id就用id查，如果带了lastName就用lastName查;只会进入其中一个 --></span>
 		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>choose</span><span class="token punctuation">></span></span>
 			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>when</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>id!=null<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
 				id=#&#123;id&#125;
 			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>when</span><span class="token punctuation">></span></span>
 			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>when</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>lastName!=null<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
 				last_name like #&#123;lastName&#125;  // 模糊查询
 			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>when</span><span class="token punctuation">></span></span>
 			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>when</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>email!=null<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
 				email = #&#123;email&#125;
 			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>when</span><span class="token punctuation">></span></span>
 			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>otherwise</span><span class="token punctuation">></span></span>
 				gender = 0 //如果上述条件都不符合，则执行此条语句
 			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>otherwise</span><span class="token punctuation">></span></span>
 		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>choose</span><span class="token punctuation">></span></span>
 	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>where</span><span class="token punctuation">></span></span>
 <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>select</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><strong>如果 id != null</strong></p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">Employee</span> employee <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Employee</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token string">"Admin"</span><span class="token punctuation">,</span> <span class="token keyword">null</span><span class="token punctuation">,</span> <span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">></span></span> emps <span class="token operator">=</span> mapper<span class="token punctuation">.</span><span class="token function">getEmpsByConditionIf</span><span class="token punctuation">(</span>employee <span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>则查询语句为</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">select</span> <span class="token operator">*</span> <span class="token keyword">from</span> tbl_employee id <span class="token operator">=</span> <span class="token number">1</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p><strong>如果 全为 null</strong></p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">Employee</span> employee <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Employee</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">,</span> <span class="token keyword">null</span><span class="token punctuation">,</span> <span class="token keyword">null</span><span class="token punctuation">,</span> <span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">></span></span> emps <span class="token operator">=</span> mapper<span class="token punctuation">.</span><span class="token function">getEmpsByConditionIf</span><span class="token punctuation">(</span>employee <span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>则查询语句为</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">select</span> <span class="token operator">*</span> <span class="token keyword">from</span> tbl_employee gender <span class="token operator">=</span> <span class="token number">0</span> <span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<h2 id="5-set-更新"><a href="#5-set-更新" class="headerlink" title="5. set 更新"></a>5. set 更新</h2><p>我们之前的更新操作语句是这样的</p>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>update</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>updateEmp<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
		update tbl_employee 
		set last_name=#&#123;lastName&#125;,email=#&#123;email&#125;,gender=#&#123;gender&#125;
		where id=#&#123;id&#125;
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>update</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>需要进行<strong>全字段更新</strong></p>
<p>比如：已有数据库信息 id = 1 , lastName = Jack, email = 123, gender = 1;</p>
<p>我们想要更新它的lastName，则：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">Employee</span> employee <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Employee</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token string">"Admin"</span><span class="token punctuation">,</span> <span class="token number">123</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">></span></span> emps <span class="token operator">=</span> mapper<span class="token punctuation">.</span><span class="token function">updateEmp</span><span class="token punctuation">(</span>employee <span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>set 标签用来执行更新操作，<strong>只更新需要更新的字段</strong>：</p>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token comment">&lt;!--public void updateEmp(Employee employee);  --></span>
	 <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>update</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>updateEmp<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
	 	<span class="token comment">&lt;!-- Set标签的使用 --></span>
	 	update tbl_employee 
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>set</span><span class="token punctuation">></span></span>
			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>lastName!=null<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
				last_name=#&#123;lastName&#125;,
			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span>
			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>email!=null<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
				email=#&#123;email&#125;,
			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span>
			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>gender!=null<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
				gender=#&#123;gender&#125;
			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>set</span><span class="token punctuation">></span></span>
		where id=#&#123;id&#125; 
	 <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>update</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>set 标签会自动剔除多余的 <code>，</code></p>
<p>比如：已有数据库信息 id = 1 , lastName = Jack, email = 123, gender = 1;<br>我们想要更新它的 lastName，则：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">Employee</span> employee <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Employee</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token string">"Admin"</span><span class="token punctuation">,</span> <span class="token keyword">null</span><span class="token punctuation">,</span> <span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">></span></span> emps <span class="token operator">=</span> mapper<span class="token punctuation">.</span><span class="token function">updateEmp</span><span class="token punctuation">(</span>employee <span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>可以看见 email 和 gender 都为空，即该字段不被更新，保持不变。</p>
<h2 id="6-foreach-遍历集合"><a href="#6-foreach-遍历集合" class="headerlink" title="6. foreach 遍历集合"></a>6. foreach 遍历集合</h2><p>foreach 标签中的属性：</p>
<ul>
<li><p>collection：指定要遍历的集合：</p>
<p>  list类型的参数会特殊处理封装在map中，map的key就叫list</p>
</li>
<li><p>item：将当前遍历出的元素赋值给指定的变量</p>
</li>
<li><p>separator ：每个元素之间的分隔符</p>
</li>
<li><p>open ：遍历出所有结果拼接一个开始的字符</p>
</li>
<li><p>close : 遍历出所有结果拼接一个结束的字符</p>
</li>
<li><p>index : 索引。遍历list的时候是index就是索引，item就是当前值</p>
<pre><code>                     遍历map的时候index表示的就是map的key，item就是map的值
</code></pre>
</li>
<li><p><code>#&#123;变量名&#125;</code> 就能取出变量的值也就是当前遍历出的元素</p>
</li>
</ul>
<h3 id="①-批量查询"><a href="#①-批量查询" class="headerlink" title="① 批量查询"></a>① 批量查询</h3><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">//查询员工id'在给定集合中的</span>
<span class="token keyword">public</span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">></span></span> <span class="token function">getEmpsByConditionForeach</span><span class="token punctuation">(</span><span class="token annotation punctuation">@Param</span><span class="token punctuation">(</span><span class="token string">"ids"</span><span class="token punctuation">)</span><span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">></span></span> ids<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token comment">&lt;!--public List&lt;Employee> getEmpsByConditionForeach(List&lt;Integer> ids);  --></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>select</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>getEmpsByConditionForeach<span class="token punctuation">"</span></span> <span class="token attr-name">resultType</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.smallbeef.mybatis.bean.Employee<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
	 	select * from tbl_employee
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>foreach</span> <span class="token attr-name">collection</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>ids<span class="token punctuation">"</span></span> <span class="token attr-name">item</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>item_id<span class="token punctuation">"</span></span> <span class="token attr-name">separator</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>,<span class="token punctuation">"</span></span><span class="token attr-name">open</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>where id in(<span class="token punctuation">"</span></span> <span class="token attr-name">close</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>)<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
	 	#&#123;item_id&#125;
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>foreach</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>select</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>测试：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">></span></span> list <span class="token operator">=</span> mapper<span class="token punctuation">.</span><span class="token function">getEmpsByConditionForeach</span><span class="token punctuation">(</span><span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">asList</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token number">4</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">Employee</span> emp <span class="token operator">:</span> list<span class="token punctuation">)</span> 
	<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>emp<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<h3 id="②-批量保存"><a href="#②-批量保存" class="headerlink" title="② 批量保存"></a>② 批量保存</h3><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">addEmps</span><span class="token punctuation">(</span><span class="token annotation punctuation">@Param</span><span class="token punctuation">(</span><span class="token string">"emps"</span><span class="token punctuation">)</span><span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">></span></span> emps<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token comment">&lt;!--public void addEmps(@Param("emps")List&lt;Employee> emps);  --></span>
 <span class="token comment">&lt;!--MySQL下批量保存：可以foreach遍历   mysql支持values(),(),()语法--></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>insert</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>addEmps<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
 	insert into tbl_employee
	values
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>foreach</span> <span class="token attr-name">collection</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>emps<span class="token punctuation">"</span></span> <span class="token attr-name">item</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>emp<span class="token punctuation">"</span></span> <span class="token attr-name">separator</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>,<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
		(#&#123;emp.lastName&#125;,#&#123;emp.email&#125;,#&#123;emp.gender&#125;,#&#123;emp.dept.id&#125;)
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>foreach</span><span class="token punctuation">></span></span>
 <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>insert</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>测试：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">testBatchSave</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">IOException</span><span class="token punctuation">&#123;</span>
	<span class="token class-name">String</span> resource <span class="token operator">=</span> <span class="token string">"mybatis-config.xml"</span><span class="token punctuation">;</span>
	<span class="token class-name">InputStream</span> inputStream <span class="token operator">=</span> <span class="token class-name">Resources</span><span class="token punctuation">.</span><span class="token function">getResourceAsStream</span><span class="token punctuation">(</span>resource<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token class-name">SqlSessionFactory</span> sqlSessionFactory <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">SqlSessionFactoryBuilder</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">build</span><span class="token punctuation">(</span>inputStream<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token class-name">SqlSession</span> openSession <span class="token operator">=</span> sqlSessionFactory<span class="token punctuation">.</span><span class="token function">openSession</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token keyword">try</span><span class="token punctuation">&#123;</span>
		<span class="token class-name">EmployeeMapperDynamicSQL</span> mapper <span class="token operator">=</span> openSession<span class="token punctuation">.</span><span class="token function">getMapper</span><span class="token punctuation">(</span><span class="token class-name">EmployeeMapperDynamicSQL</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">></span></span> emps <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayList</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		emps<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Employee</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">,</span> <span class="token string">"smith0x1"</span><span class="token punctuation">,</span> <span class="token string">"smith0x1@qq.com"</span><span class="token punctuation">,</span> <span class="token string">"1"</span><span class="token punctuation">,</span><span class="token keyword">new</span> <span class="token class-name">Department</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		emps<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Employee</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">,</span> <span class="token string">"allen0x1"</span><span class="token punctuation">,</span> <span class="token string">"allen0x1@qq.com"</span><span class="token punctuation">,</span> <span class="token string">"0"</span><span class="token punctuation">,</span><span class="token keyword">new</span> <span class="token class-name">Department</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		mapper<span class="token punctuation">.</span><span class="token function">addEmps</span><span class="token punctuation">(</span>emps<span class="token punctuation">)</span><span class="token punctuation">;</span>
		openSession<span class="token punctuation">.</span><span class="token function">commit</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span><span class="token keyword">finally</span><span class="token punctuation">&#123;</span>
		openSession<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="7-两个内置参数-databaseId-parameter"><a href="#7-两个内置参数-databaseId-parameter" class="headerlink" title="7. 两个内置参数  _databaseId / _parameter"></a>7. 两个内置参数  _databaseId / _parameter</h2><p>两个内置参数：不只是方法传递过来的参数可以被用来判断，取值</p>
<p>mybatis默认还有两个内置参数：</p>
<ul>
<li><p><code>_parameter</code> : 代表整个参数</p>
<p>单个参数：_parameter 就是这个参数</p>
<p>  多个参数：参数会被封装为一个map；_parameter就是代表这个map</p>
</li>
<li><p> <code>_databaseId</code> : 如果配置了databaseIdProvider标签。</p>
<p>   _databaseId 就是代表当前数据库的别名 oracle</p>
</li>
</ul>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token comment">&lt;!--public List&lt;Employee> getEmpsTestInnerParameter(Employee employee);  --></span>
 <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>select</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>getEmpsTestInnerParameter<span class="token punctuation">"</span></span> <span class="token attr-name">resultType</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.smakk.mybatis.bean.Employee<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>

 		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>_databaseId==<span class="token punctuation">'</span>mysql<span class="token punctuation">'</span><span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
 			select * from tbl_employee
 			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>_parameter!=null<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
 				where last_name like #&#123;lastName&#125;
 			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span>
 		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span>
 		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>_databaseId==<span class="token punctuation">'</span>oracle<span class="token punctuation">'</span><span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
 			select * from employees
 			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>_parameter!=null<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
 				where last_name like #&#123;_parameter.lastName&#125;
 			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span>
 		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span>
 <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>select</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="8-bind-绑定"><a href="#8-bind-绑定" class="headerlink" title="8. bind 绑定"></a>8. bind 绑定</h2><p>bind 元素可以从 OGNL 表达式中创建一个变量并将其绑定到上下文。<br>比如：</p>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token comment">&lt;!--public List&lt;Employee> getEmpsTestInnerParameter(Employee employee);  --></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>select</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>getEmpsTestInnerParameter<span class="token punctuation">"</span></span> <span class="token attr-name">resultType</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.atguigu.mybatis.bean.Employee<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
  		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>bind</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>_lastName<span class="token punctuation">"</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span><span class="token punctuation">'</span>%<span class="token punctuation">'</span>+lastName+<span class="token punctuation">'</span>%<span class="token punctuation">'</span><span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
  		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>_databaseId==<span class="token punctuation">'</span>mysql<span class="token punctuation">'</span><span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
  			select * from tbl_employee
  			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>_parameter!=null<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
  				where last_name like #&#123;lastName&#125;
  			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span>
  		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>select</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>测试：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">Employee</span> employee2 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Employee</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
employee2<span class="token punctuation">.</span><span class="token function">setLastName</span><span class="token punctuation">(</span><span class="token string">"e"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Employee</span><span class="token punctuation">></span></span> list <span class="token operator">=</span> mapper<span class="token punctuation">.</span><span class="token function">getEmpsTestInnerParameter</span><span class="token punctuation">(</span>employee2<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">Employee</span> employee <span class="token operator">:</span> list<span class="token punctuation">)</span> 
	<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>employee<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>lastName 的值 <code>e</code> 被 bind 拼接成 <code>%e%</code>，即由精确查询 —&gt; 模糊查询</p>
<h2 id="9-抽取可重用的-sql-片段"><a href="#9-抽取可重用的-sql-片段" class="headerlink" title="9. 抽取可重用的 sql 片段"></a>9. 抽取可重用的 sql 片段</h2><p>抽取可重用的sql片段。方便后面引用 </p>
<ul>
<li><p><code>sql</code> 抽取：经常将要查询的列名，或者插入用的列名抽取出来方便引用</p>
</li>
<li><p><code>include</code> 来引用已经抽取的sql：</p>
</li>
<li><p>include 还可以自定义一些 <code>property</code>，可在sql标签内部通过<code>$&#123;prop&#125;</code> 取出对应值</p>
<p>不能使用这种方式 <code>#&#123;prop&#125;</code></p>
</li>
</ul>
<p>示例如下：</p>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>sql</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>insertColumn<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>_databaseId==<span class="token punctuation">'</span>oracle<span class="token punctuation">'</span><span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
			employee_id,last_name,email,$&#123;testColumn&#125;
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>if</span> <span class="token attr-name">test</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>_databaseId==<span class="token punctuation">'</span>mysql<span class="token punctuation">'</span><span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
			last_name,email,gender,d_id
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>if</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>sql</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token operator">&lt;</span><span class="token keyword">insert</span> id<span class="token operator">=</span><span class="token string">"addEmps"</span> databaseId<span class="token operator">=</span><span class="token string">"oracle"</span><span class="token operator">></span>
	 	<span class="token keyword">insert</span> <span class="token keyword">into</span> employees<span class="token punctuation">(</span>
	 		<span class="token operator">&lt;</span><span class="token operator">!</span><span class="token comment">-- 引用外部定义的 sql --></span>
	 		<span class="token operator">&lt;</span>include refid<span class="token operator">=</span><span class="token string">"insertColumn"</span><span class="token operator">></span>
	 			<span class="token operator">&lt;</span>property name<span class="token operator">=</span><span class="token string">"testColomn"</span> <span class="token keyword">value</span><span class="token operator">=</span><span class="token string">"abc"</span><span class="token operator">/</span><span class="token operator">></span>
	 		<span class="token operator">&lt;</span><span class="token operator">/</span>include<span class="token operator">></span>
	 	<span class="token punctuation">)</span>
	 	<span class="token operator">&lt;</span>foreach collection<span class="token operator">=</span><span class="token string">"emps"</span> item<span class="token operator">=</span><span class="token string">"emp"</span> separator<span class="token operator">=</span><span class="token string">"union"</span>
	 		<span class="token keyword">open</span><span class="token operator">=</span><span class="token string">"select employees_seq.nextval,lastName,email from("</span>
	 		<span class="token keyword">close</span><span class="token operator">=</span><span class="token string">")"</span><span class="token operator">></span>
	 		<span class="token keyword">select</span> <span class="token comment">#&#123;emp.lastName&#125; lastName, #&#123;emp.email&#125; email from dual</span>
	 	<span class="token operator">&lt;</span><span class="token operator">/</span>foreach<span class="token operator">></span>
<span class="token operator">&lt;</span><span class="token operator">/</span><span class="token keyword">insert</span><span class="token operator">></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<hr>
<h1 id="五、缓存机制"><a href="#五、缓存机制" class="headerlink" title="五、缓存机制"></a>五、缓存机制</h1><p>MyBatis 包含一个非常强大的查询缓存特性,它可以非 常方便地配置和定制。缓存可以极大的提升查询效率。<br>MyBatis系统中默认定义了两级缓存：<strong>一级缓存</strong>和<strong>二级缓存</strong>。 </p>
<ul>
<li>默认情况下，只有一级缓存（<strong>SqlSession</strong> 级别的缓存， 也称为本地缓存）开启。 </li>
<li>二级缓存需要手动开启和配置，他是基于 <strong>namespace</strong> 级别的缓存。（也称为全局缓存） </li>
<li>为了提高扩展性。MyBatis 定义了 <code>缓存接口 Cache</code>。我们 可以通过实现 Cache 接口来自定义二级缓存</li>
</ul>
<h2 id="1-一级缓存-本地缓存"><a href="#1-一级缓存-本地缓存" class="headerlink" title="1. 一级缓存(本地缓存)"></a>1. 一级缓存(本地缓存)</h2><p>一级缓存（本地缓存）：<strong>sqlSession 级别的缓存</strong>。</p>
<ul>
<li>一级缓存是一直开启的</li>
<li>SqlSession 级别的一个 Map</li>
<li><strong>与数据库同一次会话期间查询到的数据会放在本地缓存中</strong>。以后如果需要获取相同的数据，直接从缓存中拿，没必要再去查询数据库；</li>
</ul>
<p><strong>一级缓存失效情况</strong>（没有使用到当前一级缓存的情况，还需要再向数据库重新发出sql语句进行查询）：</p>
<ul>
<li>sqlSession不同</li>
<li>sqlSession相同，查询条件不同.(当前一级缓存中还没有这个数据)</li>
<li>sqlSession相同，两次查询之间执行了增删改操作(因为这次增删改可能对当前数据有影响)</li>
<li>sqlSession相同，手动清除了一级缓存（缓存清空） <code>openSession.clearCache();</code></li>
</ul>
<h2 id="2-二级缓存（全局缓存）"><a href="#2-二级缓存（全局缓存）" class="headerlink" title="2. 二级缓存（全局缓存）"></a>2. 二级缓存（全局缓存）</h2><p>二级缓存（全局缓存）：<strong>基于namespace级别的缓存</strong>，一个namespace对应一个二级缓存 <code>&lt;mapper namespace=&quot;com.smallbeef.mybatis.dao.EmployeeMapper&quot;&gt;</code></p>
<p>工作机制：</p>
<ul>
<li><p>一个会话，查询一条数据，这个数据就会被放在当前会话的一级缓存中；</p>
</li>
<li><p>如果会话关闭，一级缓存中的数据会被保存到二级缓存中；新的会话查询信息，就可以参照二级缓存中的内容；（<strong>二级缓存只有在 SqlSession 关闭或提交之后才会生效</strong>）</p>
</li>
<li><p>不同namespace查出的数据会放在自己对应的缓存中（map）</p>
</li>
</ul>
<p><strong>使用：</strong></p>
<ul>
<li><p>（二级缓存默认不开启，需要手动配置 ）在全局配置文件中 开启全局二级缓存配置：</p>
  <pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token generics"><span class="token punctuation">&lt;</span>settings<span class="token punctuation">></span></span>	
    <span class="token operator">&lt;</span><span class="token operator">!</span><span class="token operator">--</span>显式的指定每个我们需要更改的配置的值，即使他是默认的。防止版本更新带来的问题  <span class="token operator">--</span><span class="token operator">></span>
    <span class="token operator">&lt;</span>setting name<span class="token operator">=</span><span class="token string">"cacheEnabled"</span> value<span class="token operator">=</span><span class="token string">"true"</span><span class="token operator">/</span><span class="token operator">></span>
<span class="token operator">&lt;</span><span class="token operator">/</span>settings<span class="token operator">></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre></li>
<li><p>去 <code>mapper.xml</code> 中配置使用二级缓存：<code>&lt;cache&gt;&lt;/cache&gt;</code></p>
  <pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>mapper</span> <span class="token attr-name">namespace</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.smallbeef.mybatis.dao.EmployeeMapper<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>cache</span> <span class="token attr-name">eviction</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>FIFO<span class="token punctuation">"</span></span> <span class="token attr-name">flushInterval</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>60000<span class="token punctuation">"</span></span> <span class="token attr-name">readOnly</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>false<span class="token punctuation">"</span></span> <span class="token attr-name">size</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>1024<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>cache</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>  <strong>cache标签的属性：</strong></p>
<p>  <code>eviction</code> : 缓存的回收策略：</p>
<ul>
<li>LRU (默认) – 最近最少使用的：移除最长时间不被使用的对象。</li>
<li>FIFO – 先进先出：按对象进入缓存的顺序来移除它们。</li>
<li>SOFT – 软引用：移除基于垃圾回收器状态和软引用规则的对象。</li>
<li>WEAK – 弱引用：更积极地移除基于垃圾收集器状态和弱引用规则的对象。</li>
</ul>
<p>  <code>flushInterval</code> ：缓存刷新间隔</p>
<p>  缓存多长时间清空一次，默认不清空。单位是毫秒</p>
<p>  <code>readOnly</code> : 是否只读：</p>
<ul>
<li><p>true：只读：mybatis认为所有从缓存中获取数据的操作都是只读操作，不会修改数据。</p>
<p> <strong>mybatis为了加快获取速度，直接就会将数据在缓存中的引用交给用户。不安全，速度快</strong></p>
</li>
<li><p>false：非只读 (默认)：mybatis觉得获取的数据可能会被修改。</p>
<p><strong>mybatis会利用序列化&amp;反序列的技术克隆一份新的数据给你。安全，速度慢</strong></p>
</li>
</ul>
<p>  <code>size</code> ：缓存存放多少元素；代表缓存最多可以存储多少个对象，太大容易导致内存溢出 </p>
<p>  <code>type</code> ：指定自定义缓存的全类名；(默认就是 namespace 的名称)</p>
</li>
</ul>
<blockquote>
<p>注意：POJO 需要实现序列化接口</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Employee</span> <span class="token keyword">implements</span> <span class="token class-name">Serializable</span><span class="token punctuation">&#123;</span>

<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
</blockquote>
<h2 id="3-缓存相关设置"><a href="#3-缓存相关设置" class="headerlink" title="3. 缓存相关设置"></a>3. 缓存相关设置</h2><p>和缓存有关的设置/属性：</p>
<ul>
<li><code>cacheEnabled=true</code>：开启二级缓存</li>
</ul>
<p>false：关闭缓存（二级缓存关闭）(一级缓存仍然可用)</p>
<ul>
<li>每个 <strong>select</strong> 标签都有 <code>useCache=&quot;true&quot;</code> (默认) </li>
</ul>
<p>配置这个select是否使用二级缓存。一级缓存一直是使用的 </p>
<ul>
<li>每个增删改标签默认 <code>flushCache=&quot;true&quot;</code>：sql执行以后，会同时清空一级和二级缓存。 </li>
</ul>
<p>查询标签默认 <code>flushCache=&quot;false&quot;</code> </p>
<ul>
<li><p><code>sqlSession.clearCache();</code> 清除当前session的一级缓存；</p>
</li>
<li><p>当在某一个作用域 (一级缓存Session/二级缓存 namespace) 进行了增删改 操作后，默认该作用域下所有 select 中的缓存将被 clear。    </p>
</li>
</ul>
<h2 id="4-Mybatis-的缓存原理"><a href="#4-Mybatis-的缓存原理" class="headerlink" title="4. Mybatis 的缓存原理"></a>4. Mybatis 的缓存原理</h2><p><img src="https://gitee.com/veal98/images/raw/master/img/20200523223834.png"></p>
<h2 id="5-第三方缓存-EhCache-整合"><a href="#5-第三方缓存-EhCache-整合" class="headerlink" title="5. 第三方缓存 EhCache 整合"></a>5. 第三方缓存 EhCache 整合</h2><p> EhCache 是一个纯Java的进程内缓存框架，具有快速、精 干等特点，是Hibernate中默认的CacheProvider。</p>
<p> <strong>整合步骤如下：</strong></p>
<h4 id="①-导入-ehcache-包，以及Mybatis整合包，日志包"><a href="#①-导入-ehcache-包，以及Mybatis整合包，日志包" class="headerlink" title="① 导入 ehcache 包，以及Mybatis整合包，日志包"></a>① 导入 ehcache 包，以及Mybatis整合包，日志包</h4><ul>
<li><code>ehcache-core-2.6.8.jar</code></li>
<li><code>mybatis-ehcache-1.0.3.jar</code></li>
<li><code>slf4j-api-1.6.1.jar</code></li>
<li><code>slf4j-log4j12-1.6.2.jar</code></li>
</ul>
<h4 id="②-编写ehcache-xml配置文件"><a href="#②-编写ehcache-xml配置文件" class="headerlink" title="② 编写ehcache.xml配置文件"></a>② 编写ehcache.xml配置文件</h4><p>该配置文件放在 conf 文件夹下，和 全局配置配置文件 为同级目录</p>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token prolog">&lt;?xml version="1.0" encoding="UTF-8"?></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>ehcache</span> <span class="token attr-name"><span class="token namespace">xmlns:</span>xsi</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>http://www.w3.org/2001/XMLSchema-instance<span class="token punctuation">"</span></span>
 <span class="token attr-name"><span class="token namespace">xsi:</span>noNamespaceSchemaLocation</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>../config/ehcache.xsd<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
 <span class="token comment">&lt;!-- 磁盘保存路径 --></span>
 <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>diskStore</span> <span class="token attr-name">path</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>D:\44\ehcache<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
 
 <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>defaultCache</span> 
   <span class="token attr-name">maxElementsInMemory</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>10000<span class="token punctuation">"</span></span> 
   <span class="token attr-name">maxElementsOnDisk</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>10000000<span class="token punctuation">"</span></span>
   <span class="token attr-name">eternal</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>false<span class="token punctuation">"</span></span> 
   <span class="token attr-name">overflowToDisk</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>true<span class="token punctuation">"</span></span> 
   <span class="token attr-name">timeToIdleSeconds</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>120<span class="token punctuation">"</span></span>
   <span class="token attr-name">timeToLiveSeconds</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>120<span class="token punctuation">"</span></span> 
   <span class="token attr-name">diskExpiryThreadIntervalSeconds</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>120<span class="token punctuation">"</span></span>
   <span class="token attr-name">memoryStoreEvictionPolicy</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>LRU<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
 <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>defaultCache</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>ehcache</span><span class="token punctuation">></span></span>
 <span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><strong>属性说明：</strong></p>
<ul>
<li>diskStore：指定数据在磁盘中的存储位置。</li>
<li>defaultCache：当借助 <code>CacheManager.add(&quot;demoCache&quot;)</code> 创建Cache时，EhCache便会采用 <code>&lt; defalutCache /&gt;</code> 指定的的管理策略</li>
</ul>
<p><strong>以下属性是必须的：</strong></p>
<ul>
<li>maxElementsInMemory - 在内存中缓存的element的最大数目 </li>
<li>maxElementsOnDisk - 在磁盘上缓存的element的最大数目，若是0表示无穷大</li>
<li>eternal - 设定缓存的elements是否永远不过期。如果为true，则缓存的数据始终有效，如果为false那么还要根据timeToIdleSeconds，timeToLiveSeconds判断</li>
<li>overflowToDisk - 设定当内存缓存溢出的时候是否将过期的element缓存到磁盘上</li>
</ul>
<p><strong>以下属性是可选的：</strong></p>
<ul>
<li>timeToIdleSeconds - 当缓存在EhCache中的数据前后两次访问的时间超过timeToIdleSeconds的属性取值时，这些数据便会删除，默认值是0,也就是可闲置时间无穷大</li>
<li>timeToLiveSeconds - 缓存element的有效生命期，默认是0.,也就是element存活时间无穷大</li>
<li>diskSpoolBufferSizeMB 这个参数设置DiskStore(磁盘缓存)的缓存区大小.默认是30MB.每个Cache都应该有自己的一个缓冲区.</li>
<li>diskPersistent - 在VM重启的时候是否启用磁盘保存EhCache中的数据，默认是false。</li>
<li>diskExpiryThreadIntervalSeconds - 磁盘缓存的清理线程运行间隔，默认是120秒。每个120s，相应的线程会进行一次EhCache中数据的清理工作</li>
<li>memoryStoreEvictionPolicy - 当内存缓存达到最大，有新的element加入的时候， 移除缓存中element的策略。默认是LRU（最近最少使用），可选的有LFU（最不常使用）和FIFO（先进先出）</li>
</ul>
<h4 id="③-mapper-中配置-cache标签"><a href="#③-mapper-中配置-cache标签" class="headerlink" title="③ mapper 中配置 cache标签"></a>③ mapper 中配置 cache标签</h4><pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>mapper</span> <span class="token attr-name">namespace</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.smallbeef.mybatis.dao.EmployeeMapper<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>cache</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span> <span class="token punctuation">"</span>org.mybatis.caches.ehcache.EhcacheCache<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>cache</span><span class="token punctuation">></span></span> <span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>若想在命名空间中共享相同的缓存配置和实例。 可以使用 <code>cache-ref</code> 元素来引用另外一个缓存。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token operator">&lt;</span>mapper namespace<span class="token operator">=</span><span class="token string">"com.smallbeef.mybatis.dao.DepartmentMapper"</span><span class="token operator">></span>
	<span class="token operator">&lt;</span>cache<span class="token operator">-</span>ref namespace<span class="token operator">=</span><span class="token string">"com.atguigu.mybatis.dao.EmployeeMapper"</span><span class="token operator">/</span><span class="token operator">></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<hr>
<h1 id="📚-References"><a href="#📚-References" class="headerlink" title="📚 References"></a>📚 References</h1><ul>
<li><p>😁 <a target="_blank" rel="noopener" href="https://www.bilibili.com/video/BV1zb411V77d?from=search&seid=1905892273992508442">视频 - MyBatis_尚硅谷</a></p>
<p><strong>课程配套百度网盘资源：</strong></p>
<p>链接：<a target="_blank" rel="noopener" href="https://pan.baidu.com/s/1bH-d1yBugAr0DjGzx7DGIA">https://pan.baidu.com/s/1bH-d1yBugAr0DjGzx7DGIA</a></p>
<p>提取码：nsct</p>
</li>
<li><p>🥝 公众号 江南一点雨 相关教程</p>
</li>
</ul>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">Gtwff</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://kuangty.gitee.io/2022/02/19/SSM/Mybatis/Mybatis%E7%9F%A5%E8%AF%86%E7%82%B9%E5%85%A8%E8%A7%A3/">https://kuangty.gitee.io/2022/02/19/SSM/Mybatis/Mybatis%E7%9F%A5%E8%AF%86%E7%82%B9%E5%85%A8%E8%A7%A3/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">Gtwff</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/MyBatis-%E8%AF%A6%E8%A7%A3/">
                                    <span class="chip bg-color">MyBatis 详解</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2022/02/19/SSM/Spring/SpringIoC%E5%AE%B9%E5%99%A8%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/16.jpg" class="responsive-img" alt="Spring IoC 容器源码分析">
                        
                        <span class="card-title">Spring IoC 容器源码分析</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2022-02-19
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Spring/" class="post-category">
                                    Spring
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Spring-IoC/">
                        <span class="chip bg-color">Spring IoC</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2022/02/19/SpringBoot/SpringBoot%20%E6%8C%87%E5%8D%97/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/23.jpg" class="responsive-img" alt="SpingBoot 指南">
                        
                        <span class="card-title">SpingBoot 指南</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2022-02-19
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Spring-Boot/" class="post-category">
                                    Spring Boot
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/SpingBoot-%E6%8C%87%E5%8D%97/">
                        <span class="chip bg-color">SpingBoot 指南</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h1, h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h1, h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="503838841"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    

    <div class="container row center-align"
         style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2019-2022</span>
            
            <span id="year">2019</span>
            <a href="/about" target="_blank">Gtwff</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
                &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                        class="white-color">577.4k</span>
            
            
            
                
            
            
                <span id="busuanzi_container_site_pv">
                &nbsp;|&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;
                    <span id="busuanzi_value_site_pv" class="white-color"></span>
            </span>
            
            
                <span id="busuanzi_container_site_uv">
                &nbsp;|&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;
                    <span id="busuanzi_value_site_uv" class="white-color"></span>
            </span>
            
            <br>

            <!-- 运行天数提醒. -->
            
                <span id="sitetime"> Loading ...</span>
                <script>
                    var calcSiteTime = function () {
                        var seconds = 1000;
                        var minutes = seconds * 60;
                        var hours = minutes * 60;
                        var days = hours * 24;
                        var years = days * 365;
                        var today = new Date();
                        var startYear = "2019";
                        var startMonth = "6";
                        var startDate = "28";
                        var startHour = "0";
                        var startMinute = "0";
                        var startSecond = "0";
                        var todayYear = today.getFullYear();
                        var todayMonth = today.getMonth() + 1;
                        var todayDate = today.getDate();
                        var todayHour = today.getHours();
                        var todayMinute = today.getMinutes();
                        var todaySecond = today.getSeconds();
                        var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                        var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                        var diff = t2 - t1;
                        var diffYears = Math.floor(diff / years);
                        var diffDays = Math.floor((diff / days) - diffYears * 365);

                        // 区分是否有年份.
                        var language = 'zh-CN';
                        if (startYear === String(todayYear)) {
                            document.getElementById("year").innerHTML = todayYear;
                            var daysTip = 'This site has been running for ' + diffDays + ' days';
                            if (language === 'zh-CN') {
                                daysTip = '本站已运行 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                daysTip = '本站已運行 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = daysTip;
                        } else {
                            document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                            var yearsAndDaysTip = 'This site has been running for ' + diffYears + ' years and '
                                + diffDays + ' days';
                            if (language === 'zh-CN') {
                                yearsAndDaysTip = '本站已运行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                yearsAndDaysTip = '本站已運行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = yearsAndDaysTip;
                        }
                    }

                    calcSiteTime();
                </script>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/kuangtianyu" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:1575235124@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1575235124" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1575235124" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>





    <a href="https://www.zhihu.com/people/kuang-tian-yu-59" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/people/kuang-tian-yu-59" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    
    <script type="text/javascript" color="0,0,255"
        pointColor="0,0,255" opacity='0.7'
        zIndex="-1" count="99"
        src="/libs/background/canvas-nest.js"></script>
    

    
    
    <script type="text/javascript" size="150" alpha='0.6'
        zIndex="-1" src="/libs/background/ribbon-refresh.min.js" async="async"></script>
    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
